我很好奇我是否遇到过C#中的编译器错误.(我正在使用Visual Studio 2013 Update 2.还没有Roslyn.)
以下代码会产生意外警告.年字段(或属性)应该不会,我认为,隐藏在基类中的静态年方法,因为这两个被称为非常不同 - 一个上的一个实例变量和一个类上.我不知道两者如何在名称解析中发生冲突.
我错过了什么?
更新:我知道字段和静态方法具有相同的名称.但是,调用这两个东西的方式是完全不同的,我不知道怎么会有任何混乱.换句话说,从类型系统的角度来看,公共字段"隐藏"基类的公共静态方法似乎是错误的.任何人都可以提供实际存在冲突的场景吗?
public class Timeframe
{
public readonly DateTime From;
public readonly DateTime To;
public Timeframe(DateTime from, DateTime to)
{
From = from;
To = to;
}
public static YearTimeframe Year(int year)
{
return new YearTimeframe(year);
}
// .. similar factory methods, e.g. Month and Day, omitted
}
public class YearTimeframe : Timeframe
{
// WARNING: 'YearTimeframe.Year' hides inherited member 'Timeframe.Year(int)'.
// (a public property w/ private readonly backing field has same problem)
public readonly int Year;
public YearTimeframe(int year)
: base(
new DateTime(year, 1, 1),
new DateTime(year, 12, 31, 23, 59, 59))
{
this.Year = year;
}
}
// .. similar classes, e.g. MonthTimeframe and DayTimeframe, omitted
Run Code Online (Sandbox Code Playgroud)
这不是一个错误.它在规范的3.7.1.2节中明确定义为警告:
类或结构中引入的常量,字段,属性,事件或类型会隐藏具有相同名称的所有基类成员.
...
与从外部作用域隐藏名称相反,从继承的作用域隐藏可访问的名称会导致报告警告.
"他们被调用的方式"并不是非常重要,因为你可以拥有类似的东西
public class YearTimeframe : Timeframe
{
// WARNING: 'YearTimeframe.Year' hides inherited member 'Timeframe.Year(int)'.
// (a public property w/ private readonly backing field has same problem)
public readonly int Year;
public YearTimeframe(int year)
: base(
new DateTime(year, 1, 1),
new DateTime(year, 12, 31, 23, 59, 59))
{
this.Year = year;
Method(Year);
}
private static void Method(int y)
{
Console.WriteLine("int");
}
private static void Method(Func<int, YearTimeframe> f)
{
Console.WriteLine("Func");
}
}
Run Code Online (Sandbox Code Playgroud)
现在调用哪个版本的Method?任何一个都可能有效.答案是在这种情况下简单名称Year解析为字段,因为它隐藏了基类中的静态方法.