C# enum - 为什么 *implicit* 从 0 转换有效? [英] C# enum - why does *implicit* casting from 0 work?

查看:31
本文介绍了C# enum - 为什么 *implicit* 从 0 转换有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拿这段代码:

enum En {
    val1,
    val2,
}

void Main()
{
    En plop = 1;  //error: Cannot implicitly convert type 'int' to 'En'
    En woop = 0;  //no error
}

当然,将 1 分配给 enum 类型的变量时它会失败.(打一个明确的演员,它会起作用.)

Of course it fails when assigning 1 to an enum-type variable. (Slap an explicit cast and it'll work.)

我的问题是:为什么在分配 0 时它不会失败?

My question is: why does it NOT fail when assigning 0 ?

推荐答案

这样是因为规范是这么说的...

It's this way because that's what the spec says...

这也是为什么给所有枚举一个值为 0 的项目总是一个好主意的另一个原因,因为有时您可能会以该值获得它们.

This is another reason why it's always a good idea to give all your enums an item with value 0, 'cos you're likely to get them with that value sometimes.

C# 语言规范 6.1.3 中的相应部分:

The appropriate section in the C# language spec 6.1.3:

6.1.3 隐式枚举转换

隐式枚举转换允许将十进制整数文字 0 转换为任何枚举类型和任何可空类型,其基础类型是枚举类型.在后一种情况下,通过转换为基础枚举类型并包装结果来评估转换(第 4.1.10 节).

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result (§4.1.10).

至于为什么是这样 - 好吧,我想只有语言委员会中决定这些事情的人会知道.

As to why it's that way - well, I guess only someone on the language committee that decides these things would know.

事实上,如果您查看 rawling 对原始问题的评论,我们确实有类似的想法.

In fact, we do have something like that if you look at rawling's comment to the original question.

这篇关于C# enum - 为什么 *implicit* 从 0 转换有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆