Why is overriding static method alowed in C#

前端 未结 6 1175
陌清茗
陌清茗 2021-02-06 06:55
protected static new void WhyIsThisValidCode()
{
}

Why are you allowed to override static methods? Nothing but bugs can come from it, it doensn\'t work

6条回答
  •  太阳男子
    2021-02-06 07:11

    You aren't overriding the property in the base class, but instead hiding it. The actual property used at runtime depends on what interface you're working against. The following example illustrates:

    SpecificLogger a = new SpecificLogger();
    BaseLogger b = new SpecificLogger();
    
    Console.Write(a.Log); // Specific
    Console.Write(b.Log); // null
    

    In your code the Log method is actually working against the BaseLogger interface - because the Log method is part of the BaseLogger class.

    Static methods and properties can not be overridden, and when you want to hide a property you should use the new keyword to denote that you're hiding something.

提交回复
热议问题