为什么属性隐藏具有相同名称的Inherited函数? [英] Why is a property hiding Inherited function with same name?
问题描述
我有一个 Foo
的类,其中包含函数 myName
。
Class bar
继承自 Foo
并拥有一个名为 myName
I have a class Foo
with a function myName
in it.
Class bar
Inherits from Foo
and have a Property that is also called myName
我认为这应该没问题,因为:
I figured this should be OK since:
- 属性将编译到
get_myName()
(因此不会与Foo :: myName(int,int)
发生冲突) -
Foo :: myName
有参数,显然,属性没有(再次,没有colision)。
- The property will compile to
get_myName()
(so there would not be a collision withFoo::myName(int,int)
) Foo::myName
has arguments while, obviously, the property does not (again, no colision).
但我仍然收到警告:
'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
函数:
Also, If I add to bar
the function:
int get_myName()
{
return a+b;
}
正如预期的那样,我收到有关先前声明的函数的错误。
那么这里发生了什么?除了 get_myName()
?
As expected, I get an error about the function previously declared.
So what is happening here? Is the property not allowing me to use ALL overloads of myName
in addition to get_myName()
?
推荐答案
C#规范的第10.3.3节包含:
Section 10.3.3 of the C# spec contains:
派生类可以通过声明具有相同名称或签名的新成员来隐藏继承的成员。
它没有说两个成员必须是同一类成员。请注意,即使一个属性是属性而另一个是方法,但仍然存在可能混淆的情况:
It doesn't say anything about the two members having to be the same kind of member. Note that even though one is a property and one is a method, there are still cases where they could be confused:
- 该属性可能是代表类型,例如
操作< int,int>
在这种情况下PropertyName(10,10)
将有效。 - 在某些使用属性名称的地方,您可能正在尝试执行方法组转换,因此它们都有效。
- The property could be of a delegate type, e.g.
Action<int, int>
in which casePropertyName(10, 10)
would be valid. - In some places where you use the property name, you could be trying to perform a method group conversion, so they'd both be valid.
在同一个班级中,我们遇到第10.3节的规则:
Within the same class, we run into the rules of section 10.3:
- 常量,字段,属性,事件或类型的名称必须与同一类中声明的所有其他成员的名称不同。
- 方法的名称必须与名称不同在同一类中声明的所有其他非方法。 [...]
您无法声明名为<$ c的方法的事实$ c> get_myName 在第10.3.9.1节中提及,如评论中所述。
The fact that you can't declare a method called get_myName
is mentioned in section 10.3.9.1, as noted in comments.
这篇关于为什么属性隐藏具有相同名称的Inherited函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!