任何人都可以解释这个有趣的C#问题吗?

前端之家收集整理的这篇文章主要介绍了任何人都可以解释这个有趣的C#问题吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我以前在一个新的控制台应用程序中复制了一个奇怪的问题.我想知道,任何人都可以解释为什么会发生这种情况吗?
  1. static void Main(string[] args)
  2. {
  3. DoSomething(0);
  4.  
  5. Console.Read();
  6. }
  7.  
  8. public static void DoSomething(int? value)
  9. {
  10. Console.WriteLine("Do Something int? called");
  11. }
  12.  
  13. public static void DoSomething(MyEnum value)
  14. {
  15. Console.WriteLine("Do Something MyEnum called");
  16. }
  17.  
  18. public static enum MyEnum : int
  19. {
  20. test
  21.  
  22. }
  23. }

您在DoSomething行中收到错误

Error 1 The call is ambiguous between the following methods or properties: ‘DoSomething(int?)’ and ‘DoSomething(MyEnum)’

但是,如果将零更改为任何其他数字,则不会有这样的问题.

解决方法

C#语言规范说明了从整数文字0到任何枚举类型的隐式转换:

13.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type.

因此,任何其他整数文字只能转换为int?因此是明确的;但是文字0可以转换成两个int?和你的枚举

您的枚举中定义了哪些值无关紧要.即使你有一个枚举,如枚举Test {Cats = 7},以上仍然适用.请记住,所有枚举都可以具有其基础整数类型的所有值,并不限于实际声明的值.

猜你在找的C#相关文章