我觉得 Enum.Format() 的第一个参数有点多余

I feel that the 1st argument of Enum.Format() is a bit redundant

我遇到了代码问题:

enum Days
{
    day1,
    day2,
    day3
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Enum.Format(typeof(Days), Days.day2, "D"));
    }
}

我觉得 Enum.Format() 的第一个参数是多余的:因为第二个参数已经指定了 Enum 的类型,所以编译器会得到 "day2" 类型的信息 "Days"。那为什么 compile 不能自己推断第一个参数是 "typeof(Days)",为什么我必须指定它?

换句话说,我的意思是,如果 Enum.Format 的 .net 函数只有 2 个参数,为什么不能呢?可以从值参数中知道类型。

因为可以在value参数中使用enum的底层类型,比如:

public enum MyEnum
{
    Foo = 1
}

string str = Enum.Format(typeof(MyEnum), 1, "G"); // Foo

但请注意:

public enum MyEnum : long
{
    Foo = 1
}

string str = Enum.Format(typeof(MyEnum), 1L, "G");

如我所写,您必须使用底层类型!所以在这种情况下,long.

这在 Enum.Format:

中有非常间接的说明

ArgumentException: The type of value is not an underlying type of enumType.

所以隐含地,如果 valueenumType 的基础类型,则没有异常并返回一些结果。