什么是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. :)