Java 静态块相当于 C# 静态构造函数吗?

发布于 2024-08-25 12:14:48 字数 113 浏览 4 评论 0原文

C# 静态构造函数和 Java 静态块之间的真正区别是什么?

它们都必须是无参数的。 当相关类首次使用时,它们都只被调用一次。

我是否遗漏了什么,或者它们是同一件事,只是名称不同?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

辞慾 2024-09-01 12:14:48

它们是等效的,只是 C# 类只能有一个静态构造函数(加上静态字段初始值设定项)。

此外,在 C# 中,static 构造函数将应用 beforefieldinit 标志

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.

遗弃M 2024-09-01 12:14:48

它们看起来相同,下面的示例显示,c# 静态构造函数与 java 中的静态块的工作方式相同

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

    private static readonly Singleton INSTANCE;

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

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();
        }
    }
勿挽旧人 2024-09-01 12:14:48

是的 他们是等价的
还有一点是java不支持静态构造函数,但支持静态块,而c#支持静态构造函数。

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

后eg是否自 2024-09-01 12:14:48

他们不是。

在 C# 中,块只能保存构造函数。在java中你可以执行语句。

They are not.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文