Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

c# - Why is a property hiding Inherited function with same name?

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:

  1. The property will compile to get_myName() (so there would not be a collision with Foo::myName(int,int))
  2. 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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 case PropertyName(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...