小编Mag*_*gus的帖子

为什么字节提升为枚举?

在使用具有多个采用不同数据类型但没有枚举的重载的外部 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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我很惊讶地发现代码无法编译,因为Overloaded((byte) 0)

以下方法或属性之间的调用不明确:“Program.Overloaded(int)”和“Program.Overloaded(Values)”

byte不能自动提升为Values,即Values v = (byte)b无法编译,因为:

无法将类型“byte”隐式转换为“TestEnumPromotion.Values”。

所以唯一可能的重载应该是 int,对吗?

我认为枚举可能只是语法糖,编译器会生成接收 int …

c# enums

4
推荐指数
1
解决办法
214
查看次数

标签 统计

c# ×1

enums ×1