为什么以下两个代码示例会产生不同的输出?
情况1
我感到困惑。这是不是意味着在基类中声明的Func(int)被Func(EnumType)隐藏了?如果是这种情况,那么为什么第二个例子中文字面量0会被隐式转换为EnumType而没有警告呢? 编辑: 当我尝试时,还有更有趣的行为。
有什么想法,为什么0和1被不同对待?
编辑2: 事实证明,在C#中,字面上的0确实具有特殊含义。
在此链接和链接中,我找到了一个对这种行为的优秀描述(请参见被接受的答案)。
enum EnumType
{
First,
Second,
Third
}
class ClassB
{
public string Func(int index)
{
return "Func(int)";
}
public string Func(EnumType type)
{
return "Func(EnumType)";
}
}
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(EnumType.First));
Console.ReadLine();
}
}
输出:
Func(int)
Func(EnumType)
Case 2
enum EnumType
{
First,
Second,
Third
}
class ClassA
{
public string Func(int index)
{
return "Func(int)";
}
}
class ClassB : ClassA
{
public string Func(EnumType enumType)
{
return "Func(EnumType)";
}
}
class Program
{
static void Main(string[] args)
{
ClassB b = new ClassB();
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(EnumType.First));
Console.ReadLine();
}
}
输出:
Func(EnumType)
Func(EnumType)
我感到困惑。这是不是意味着在基类中声明的Func(int)被Func(EnumType)隐藏了?如果是这种情况,那么为什么第二个例子中文字面量0会被隐式转换为EnumType而没有警告呢? 编辑: 当我尝试时,还有更有趣的行为。
Console.WriteLine(b.Func(0));
Console.WriteLine(b.Func(1));
Console.WriteLine(b.Func(EnumType.First));
你认为输出应该是什么样子?
这就是它的样子:
Func(EnumType)
Func(int)
Func(EnumType)
有什么想法,为什么0和1被不同对待?
编辑2: 事实证明,在C#中,字面上的0确实具有特殊含义。
在此链接和链接中,我找到了一个对这种行为的优秀描述(请参见被接受的答案)。