Why is a property hiding Inherited function with same name?

前端 未结 2 1777
日久生厌
日久生厌 2021-01-21 03:59

I have a class Foo with a function myName in it.
Class bar Inherits from Foo and have a Property that is also called

相关标签:
2条回答
  • 2021-01-21 04:20

    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.

    0 讨论(0)
  • 2021-01-21 04:26

    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'

    0 讨论(0)
提交回复
热议问题