开发者

When do static declarations get run?

Here's a piece of my code:

public class MyClass {
  public object Value { get; set; }

  public MyClass(object value) {
    this.Value = value;
  }
}

public class AnotherClass {
  private static MyClass _MyObj = new MyClass(new object());

  public static void Main(string[] args) {
    var x = _MyObj; // no problem
    var y = x.Value; // no problem
    var z = y.ToString(); // Null ref exception
  }
}

I don't understand how this can be. _MyObj is not null, which means that the inline assignment did work, yet _MyObj.Value comes out null, meaning that the constructor code wasn't invoked! There's some dark magic at work here, and I'd greatly appreciate an explanation.

Thanks!

EDIT - sorry about t开发者_如何学JAVAhe no repro. My actual code is (obviously) more complex than this, so I tried to dumb it down, and obviously in the process I must have removed some other obstruction to the code's proper function. But Kobi's answer is really what I was trying to get out of this question, anyway - so answer credit to him. :)


The proper way to initialize static members is by using a static constructor:

static AnotherClass(){
  _MyObj = new MyClass(new object());
}


Status: No repro.

The code sample as provided does not compile, public object Value { get; } is not a valid auto-property.

After fixing it with a private set; it compiles and runs w/o error.


Put a setter and it will work as expected:

public object Value { get; set; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜