c# - 意外的 C# 警告 : instance member hides static method on base class

标签 c#

我很好奇我是否在 C# 中遇到了编译器错误。 (我正在使用 Visual Studio 2013 Update 2。还没有 Roslyn。)

以下代码会产生意外警告。我认为 Year 字段(或属性)不应该隐藏基类上的静态 Year 方法,因为两者的调用方式非常不同——一个在实例变量上,一个在类上。我看不出两者在名称解析中如何发生冲突。

我错过了什么?

更新:我知道该字段和静态方法具有相同的名称。但是,调用这两个东西的方式是完全不同的,我不明白怎么可能有任何混淆。换句话说,从类型系统的角度来看,说公共(public)字段“隐藏”了基类的公共(public)静态方法似乎是错误的。谁能提供一个实际存在冲突的场景?

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

最佳答案

这不是错误。在规范的第 3.7.1.2 节中明确定义为警告:

A constant, field, property, event, or type introduced in a class or struct hides all base class members with the same name.
...
Contrary to hiding a name from an outer scope, hiding an accessible name from an inherited scope causes a warning to be reported.



“调用它们的方式”并不是非常重要,因为你可以有类似的东西
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");
    }
}

现在调用的是哪个版本的方法?任何一个都可能有效。答案是在这种情况下,简单名称 Year 解析为字段,因为它对基类隐藏了静态方法。

关于c# - 意外的 C# 警告 : instance member hides static method on base class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25144118/

相关文章:

c# - 我应该如何将域对象的属性传输到其模型对应项?

c# - 我可以在 C# 中以字节为单位获取 Session 对象的大小吗?

c# - 当 ShowInTaskbar = false 时将另一个进程窗口置于前台

c# - 关于 .net 中 XML 反序列化的问题

c# - 在 C# 中格式化日期时间

c# - 如何通过添加属性在未初始化的情况下访问属性时发出警告?

c# - 在变量声明中使用 "var"类型

c# - WPF DataGrid 无法重现 WindowsForms 数据网格大小调整行为

c# - c# 中 ref 和 out 参数之间哪个更轻

c# - 如何获取变量的编译时类型?