Why is overriding static method alowed in C#

前端 未结 6 1183
陌清茗
陌清茗 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:24

    You're not overriding it, you're hiding it. A normal method would exhibit exactly the same behavior so there is nothing specific to static methods here.

    Hiding is only useful in a few cases. The one where I came across most often is making the return type more specific in a derived class. But I never had that occur with static methods.

    One area where static functions with a certain name might be useful is if you use reflection and want to get information on each class by returning it from a method. But of course in most cases an attribute fits better.

    And it's not likely to create bugs since your code produces a compiler-warning:

    Warning 'StaticHiding.SpecificLogger.LogName' hides inherited member 'StaticHiding.BaseLogger.LogName'. Use the new keyword if hiding was intended.

    And if you use new you should know what you're doing.

提交回复
热议问题