Why Are Parentheses Required on C# Static Constructors?

删除回忆录丶 提交于 2019-12-10 20:26:45

问题


Consider:

class Foo
{
    static Foo()
    {
        // Static initialisation
    }
}

Why are the () required in static Foo() {...}? The static constructor must always be parameterless, so why bother? Are they necessary to avoid some parser ambiguity, or is it just to maintain consistency with regular parameterless constructors?

Since it looks so much like an initialiser block, I often find myself leaving them out by accident and then have to think for a few seconds about what is wrong. It would be nice if they could be elided in the same way.


回答1:


I get this sort of question frequently; that is, the question "the compiler could work out that this thing is missing, so why is it required?" Here's another example of this sort of question:

C# using consts in static classes

As I noted in that question, basically we have three choices in that situation. Make the redundant text required, make it optional, or make it illegal.

Each has its own downside.

The downside of making it required is you end up with an unnecessary redundancy in the language.

The downside of making it optional is you confuse people who think there must be a difference between the two forms. Also, you make it harder for the error-recovering parser to do its work; it thrives on redundancy. And you potentially make it harder to add new language features in the future, because more "syntactic area" is already claimed.

The downside of making it illegal is you then make a "gotcha", where the user has to remember that oh, yeah, I'm supposed to put parens here, but not here.

The proposed feature had better have an upside that pays for the downside. The smallest downside seems to me to be the first: make it required. The other options I would want to have an upside that justifies the downside, and I'm not seeing one here.




回答2:


Because it's a static constructor, so it's static + a normal-looking constructor.

Consistency is key. :-)




回答3:


I would assume it's for disambiguity: it makes the parser's job easier, recognising the code block as a constructor subroutine (irrespective of staticness); and conversely it helps ensure that the human author/maintainer is aware of the implications of choosing this particular construct, by forcing them to use a specific method-like syntax.



来源:https://stackoverflow.com/questions/6092670/why-are-parentheses-required-on-c-sharp-static-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!