Java 中静态 {...} 的 C# 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1201992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is the c# equivalent of static {...} in Java?
提问by peter.murray.rust
In Java I can write:
在 Java 中,我可以写:
public class Foo {
public static Foo DEFAULT_FOO;
static {
DEFAULT_FOO = new Foo();
// initialize
DEFAULT_FOO.init();
}
public Foo() {
}
void init() {
// initialize
}
}
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?
如何在 C# 中获得相同的功能(在使用之前初始化静态成员)?而且,如果尝试这样做是件坏事,那么更好的方法是什么?
采纳答案by Randolpho
you use a static constructor, like this:
您使用静态构造函数,如下所示:
public class Foo
{
static Foo()
{
// inits
}
}
Here's more info.
这里有更多信息。
Bottom line: it's a paramaterless constructor with the static
keyword attached to it. Works just like the static block in Java.
底线:它是一个static
附加了关键字的无参数构造函数。就像 Java 中的静态块一样工作。
Edit: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();
}
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. :)
请记住,如果您想在静态初始化期间调用 Bar 上的任何方法,您将需要一个静态构造函数,因此您调用的示例Foo.Init()
仍然需要一个静态构造函数。我只是说你不受限制,就是这样。:)
回答by Reed Copsey
Static is still the keyword in C#:
静态仍然是 C# 中的关键字:
public class Foo {
public static Foo DefaultFoo;
static Foo {
DefaultFoo = new Foo();
// initialize
DefaultFoo.init();
}
public Foo() {
}
void init() {
// initialize
}
}