c# – 为什么我不能通过单个隐式转换为枚举来打开一个类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 为什么我不能通过单个隐式转换为枚举来打开一个类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2644字,纯文字阅读大概需要4分钟。
内容图文
![c# – 为什么我不能通过单个隐式转换为枚举来打开一个类](/upload/InfoBanner/zyjiaocheng/798/8ccd3f8f57b246cf8607a364a30815b0.jpg)
我想知道为什么单个隐式转换为枚举值的方式与转换为系统类型时的方式不同.我看不出任何技术上的原因,但也许有人比我更聪明,能给我带来一些启示.
后续编译无法编译,“期望的整数类型的值”和“不能隐式地将类型’Test.En’转换为’Test.Foo’.
void test1 (){
Foo f = new Foo();
switch (f) // Comment this line to compile
//switch ((En)f) // Uncomment this line to compile
{
case En.One:
break;
}
}
//////////////////////////////////////////////////////////////////
public enum En
{
One,
Two,
Three,
}
public class Foo
{
En _myEn;
public static implicit operator En(Foo f)
{
return f._myEn;
}
}
从规范编辑:
switch语句的控制类型由switch表达式建立.如果switch表达式的类型是sbyte,byte,short,ushort,int,uint,long,ulong,char,string或enum-type,那么这就是switch语句的管理类型.否则,从switch表达式的类型到以下可能的控制类型之一,必须存在一个用户定义的隐式转换(第6.4节):sbyte,byte,short,ushort,int,uint,long,ulong,char,string .如果不存在此类隐式转换,或者存在多个此类隐式转换,则会发生编译时错误.
为了澄清这个问题,为什么枚举类型不包含在允许的用户定义的隐式转换列表中?
解决方法:
语言设计说明存档不能为此决策提供理由.这是不幸的,因为决定已经改变.如您所见,设计随着时间的推移而发展:
1999年5月26日的笔记:
What types are allowed in as the
argument to a switch statement?
integral types including char, enum
types, bool. C# also permits types
that can be implicitly and
unambiguously converted to one of the
aforementioned types. (If there are
multiple implicit conversion, then its
ambiguous and a compile-time error
occurs.) We’re not sure whether we
want to support string or not.
1999年6月7日:
We discussed enabling switch on string
arguments. We think this is a good
feature – the language can add value
by making this common case easier to
write, and the additional complexity
for the user is very low.
1999年12月20日:
It is illegal to switch on an
expression of type bool. It is legal
to switch on an expression of an
integral type or string type. It is
legal to switch on an expression of a
type that has exactly one implicit
conversion to an integral type or
string type.
在这里,我们首次出现了相关规则. Enum似乎已经消失了.为什么不使用用户定义的隐式转换来枚举?这只是一个疏忽吗?设计师没有记录他们的想法.
请注意,第一句话不是我们实施的.我不清楚为什么实现者与设计委员会推荐的相反.几年之后,这在笔记中又出现了:
2003年8月13日:
The compiler allows switch on bool.
Don’t want to document this and add it
to the language. Don’t want to remove
it for compatibility reasons. Decided
to silently continue to support switch
on bool.
我觉得这很傻;当我们制作C#3.0规范的注释印刷版时,我将bool(和bool?)添加到法律管理类型列表中.
简而言之:整件事情有点混乱.我不知道为什么枚举进入,然后出局,然后是半成半.这可能必须是未知之谜之一.
内容总结
以上是互联网集市为您收集整理的c# – 为什么我不能通过单个隐式转换为枚举来打开一个类全部内容,希望文章能够帮你解决c# – 为什么我不能通过单个隐式转换为枚举来打开一个类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。