什么是C#等效静的{...}在Java中? [英] what is the c# equivalent of static {...} in Java?

查看:139
本文介绍了什么是C#等效静的{...}在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中我可以这样写:

In Java I can write:

public class Foo {

    public static Foo DEFAULT_FOO;

    static {
        DEFAULT_FOO = new Foo();
        // initialize 
        DEFAULT_FOO.init();
    }

    public Foo() {
    }

    void init() {
        // initialize
    }
}

我怎样才能得到相同的functionailty在C#中(其中静态成员在使用前进行初始化) ?而且,如果这是一件坏事,试图做的,什么是更好的方法?

How can I get the same functionailty in C# (where static members are initialized before use)? And, if this is a bad thing to try to do, what is a better approach?

推荐答案

在使用静态构造函数,像这样的:

you use a static constructor, like this:

public class Foo
{
  static Foo()
  {
     // inits
  }
}

下面的的more信息

底线:这是一个paramaterless构造与静态关键字连接到它。作品就像Java中的静态块。

Bottom line: it's a paramaterless constructor with the static keyword attached to it. Works just like the static block in Java.

编辑:一件事提了。如果你只是想静态构造的东西,你可以静态初始化的变量,而不需要对静态构造函数。例如:

One more thing to mention. If you just want to construct something statically, you can statically initialize a variable without the need for the static constructor. For example:

public class Foo
{
  public static Bar StaticBar = new Bar();
}

请记住,如果你想打电话,你需要一个静态构造函数静态初始化期间呼吁酒吧的任何方法,让你的例子 Foo.Init()仍然需要一个静态构造函数。我只是说'你没有限制,仅此而已。 :)

Keep in mind that you'll need a static constructor if you want to call any methods on Bar during static initialization, so your example that calls Foo.Init() still needs a static constructor. I'm just sayin' you're not limited, is all. :)

这篇关于什么是C#等效静的{...}在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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