为什么需要括号在C#静态构造? [英] Why Are Parentheses Required on C# Static Constructors?

查看:192
本文介绍了为什么需要括号在C#静态构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

 类Foo 
{
静态的Foo()
{
//初始化静态
}
}

为什么是()要求静态的Foo(){...} ?静态构造函数必须始终参,何必呢?难道他们必须避免一些分析器歧义,还是它只是为了保持与常规参数构造函数的一致性?



由于它看上去非常像一个初始化器块,我经常发现自己离开他们出意外,然后不得不考虑关于什么是错的几秒钟。 。这将是很好,如果他们能以同样的方式被省略


解决方案

我得到这样的问题频繁;也就是说,这个问题,编译器可以工作了,这东西丢失,那么为什么需要它?下面是这类问题的一个例子:



使用静态类consts



正如我在这个问题指出,基本上我们在这种情况下三种选择。让需要多余的文本,使之选,或使其非法的。



每个都有自己的缺点。



使得它需要的是你最终在语言中的不必要的冗余的缺点。



使其成为可选的缺点是你分不清谁认为必须有一个人这两种形式之间的差异。另外,你要困难些错误,恢复解析器来完成其工作;它依靠的是冗余。而且你有可能使其难以在未来增加新的语言特性,因为更多的语法区已经声称。



使其非法的缺点是,那么你做一个疑难杂症,用户必须记住哦,是啊,我应该把这里的括号,但不是在这里。



建议的功能,最好有该支付下行的上涨空间。最小的缺点在我看来,是第一个:让需要。其他选项我会希望有一个证明下行的上攻,而我没有看到一个在这里。


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.

解决方案

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.

这篇关于为什么需要括号在C#静态构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆