我有一个 Foo
类,里面有一个函数 myName
。
类 bar
继承自 Foo
并具有一个也称为 myName
我认为这应该没问题,因为:
- property will compile到
get_myName()
(这样就不会与Foo::myName(int,int)
发生冲突) 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/