问题
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:
- 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).
Yet I still get the warning:
'Bar.myName' hides inherited member 'Foo.myName(int, int)'. Use the new keyword if hiding was intended.
Example Code:
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;
}
}
}
Also, If I add to bar
the function:
int get_myName()
{
return a+b;
}
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()
?
回答1:
Section 10.3.3 of the C# spec contains:
A derived class can hide inherited members by declaring new members with the same name or signature.
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:
- 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.
Within the same class, we run into the rules of section 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. [...]
The fact that you can't declare a method called get_myName
is mentioned in section 10.3.9.1, as noted in comments.
回答2:
We don't even need inheritance in the picture - you can't have "overloads" between a property and a method:
class Program
{
static void Main(string[] args)
{
Console.ReadLine();
}
void DoStuff(int i,int j)
{
}
int DoStuff { get { return 10; } }
}
Produces:
error CS0102: The type 'ConsoleApplication4.Program' already contains a definition for 'DoStuff'
来源:https://stackoverflow.com/questions/17986680/why-is-a-property-hiding-inherited-function-with-same-name