c# - 为什么属性隐藏同名的继承函数?

标签 c# .net inheritance properties

我有一个 Foo 类,里面有一个函数 myName
bar 继承自 Foo 并具有一个也称为 myName

的属性

我认为这应该没问题,因为:

  1. property will compileget_myName()(这样就不会与 Foo::myName(int,int) 发生冲突)
  2. Foo::myName 有参数,而显然该属性没有(同样,没有冲突)。

但我仍然收到警告:

'Bar.myName' hides inherited member 'Foo.myName(int, int)'. Use the new keyword if hiding was intended.

示例代码:

public class Foo
{
    public int myName(int a, int b)
    {
        return 0;
    }
}

class Bar: Foo
{
    int a;
    int b;

    int myName
    {
        get
        {
            return a + b;
        }
    }
}

此外,如果我向 bar 添加函数:

int get_myName() 
{
    return a+b;
}

如预期的那样,我得到了关于先前声明的函数的错误。
那么这里发生了什么?除了 get_myName() 之外,该属性是否不允许我使用 myName 的所有重载?

最佳答案

C# 规范的第 10.3.3 节包含:

A derived class can hide inherited members by declaring new members with the same name or signature.

它没有说明两个成员必须是同一类型的成员。请注意,尽管一个是属性,一个是方法,但仍有可能混淆它们的情况:

  • 该属性可以是委托(delegate)类型,例如Action<int, int>在这种情况下 PropertyName(10, 10)将是有效的。
  • 在某些使用属性名称的地方,您可能会尝试执行方法组转换,因此它们都是有效的。

在同一个类(class)中,我们遇到了 10.3 节的规则:

  • The names of constants, fields, properties, events, or types must differ from the names of all other members declared in the same class.
  • The name of a method must differ from the names of all other nonmethods declared in the same class. [...]

您无法声明名为 get_myName 的方法这一事实如评论中所述,在第 10.3.9.1 节中提到。

关于c# - 为什么属性隐藏同名的继承函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17986680/

相关文章:

javascript - 是否可以在 javascript 的子类的覆盖版本中使用父类的方法?

c# - 带滚动条的控件上的 .NET C# MouseEnter 监听器

c# - 设置像素数据的最佳方法?

c# - DbContext 与 Ninject ADO.NET

c# - 在另一个表格中设置表格宽度未反射(reflect)在创建的 pdf 中

android - Parcelable 和继承

asp.net - 带有身份的 ASP.NET Core 2.0 中的 Cookie 过期

.net - "Could not establish trust relationship for the SSL/TLS secure channel"具有有效证书

c# - 如何测试当前是否正在写入文件

entity-framework - 域实体跟踪数据的最佳实践?基类还是组合?