Is a Java static block equivalent to a C# static constructor?

孤者浪人 提交于 2019-12-30 03:05:06

问题


What is the real difference between a C# static constructor and a Java static block?

They both must be parameterless. They are both called only once, when the related class is first used.

Am I missing something, or are they the same thing, just with different names?


回答1:


They are equivalent, except that a C# class can only have one static constructor (plus static field initializers).

Also, in C#, a static constructor will apply the beforefieldinit flag.




回答2:


They look the same, the following example shows, that c# static constructor works the same as static block in java

protected Singleton()
{
    Console.WriteLine("Singleton constructor");
}

    private static readonly Singleton INSTANCE;

    static Singleton() {
        try {
           INSTANCE = new Singleton();
        }
        catch(Exception e) {
            throw new Exception();
        }
    }



回答3:


Yes They are equivalent Another point is java does not support static constructor but support static block and c# support static constructor.




回答4:


They are not.

In C#, there blocks can only hold constructors. In java you are able to execute statements.



来源:https://stackoverflow.com/questions/2465251/is-a-java-static-block-equivalent-to-a-c-sharp-static-constructor

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