Is a Java static block equivalent to a C# static c

2019-02-06 11:10发布

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?

4条回答
Lonely孤独者°
2楼-- · 2019-02-06 11:33

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

查看更多
够拽才男人
3楼-- · 2019-02-06 11:36

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();
        }
    }
查看更多
Summer. ? 凉城
4楼-- · 2019-02-06 11:47

They are not.

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

查看更多
祖国的老花朵
5楼-- · 2019-02-06 11:50

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.

查看更多
登录 后发表回答