首页 / C# / c# – 为什么Byte被提升为枚举?
c# – 为什么Byte被提升为枚举?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 为什么Byte被提升为枚举?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2235字,纯文字阅读大概需要4分钟。
内容图文
![c# – 为什么Byte被提升为枚举?](/upload/InfoBanner/zyjiaocheng/797/d9fe14de56b24476937fac4b845af3cf.jpg)
虽然使用具有多个重载但需要不同数据类型但没有枚举的外部API,我决定创建一个方便的方法来为枚举提供更多的类型安全性,最终得到如下内容:
namespace TestEnumPromotion
{
enum Values
{
Value0,
Value1,
}
class Program
{
static void Main(string[] args)
{
// Prints int
Overloaded(0);
// Prints Values
Overloaded(Values.Value0);
// Does not compile! :-/
Overloaded((byte) 0);
// Prints int
byte b = 0;
Overloaded(b);
}
static void Overloaded(int i)
{
Console.WriteLine("int");
}
static void Overloaded(Values i)
{
Console.WriteLine("Values");
}
}
}
但是我很惊讶地发现代码没有编译因为Overloaded((byte)0):
The call is ambiguous between the following methods or properties: ‘Program.Overloaded(int)’ and ‘Program.Overloaded(Values)’
但是字节不能自动提升为Values,即值v =(byte)b将无法编译,因为:
Cannot implicitly convert type ‘byte’ to ‘`TestEnumPromotion.Values`’.
所以唯一可能的重载应该是int,对吗?
我认为可能枚举只是语法糖,编译器会生成接收int的方法,但通过ILDASM查看IL表明实际创建了一个接受枚举的方法.
.method private hidebysig static void Overloaded(valuetype TestEnumPromotion.Values i) cil managed
{
// Code size 13 (0xd)
.maxstack 8
IL_0000: nop
IL_0001: ldstr "Values"
IL_0006: call void [mscorlib]System.Console::WriteLine(string)
IL_000b: nop
IL_000c: ret
} // end of method Program::Overloaded
怎么了?
解决方法:
这是语言中一个奇怪的小规则的结果:文字0可以隐式转换为任何枚举.
更新:根据评论和链接源,编译器实际上不遵循规范.编译器允许隐式转换任何零常量,而不仅仅是字零.您可以阅读有关此问题的更多信息here.
这不会编译:
Values someValue = 1; //can not implicitly convert `int` to...
但有趣的是,这将:
Values someValue = 0;
在您的情况下,因为(byte)0(常量零)可以隐式转换为Values和int,所以编译器无法选择最佳重载并且无法解析调用.如果将代码更改为(byte)1或任何其他文字值,它将编译得很好.
值得一提的是,Overloaded(0)的工作原理仅仅是因为编译器找到了完全匹配;不需要隐式转换,所以Overloaded(int i)赢得无争议.
引用c#4.0规范:
1.10 (…) The default value of any enum type is the integral value zero converted to the enum type. In cases where variables are automatically initialized to a default value, this is the value given to variables of enum types. In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type.(…)
内容总结
以上是互联网集市为您收集整理的c# – 为什么Byte被提升为枚举?全部内容,希望文章能够帮你解决c# – 为什么Byte被提升为枚举?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。