收录日期:2019/03/20 19:56:15 时间:2009-07-29 18:01:38 标签:c#,java,static

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
    }
}

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
  }
}

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.

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. :)

Static is still the keyword in C#:

public class Foo {
    public static Foo DefaultFoo;

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

    public Foo() {
    }

    void init() {
        // initialize
    }
}