开发者

Is it okay to refer to "this" in the constructor?

开发者 https://www.devze.com 2023-02-12 15:10 出处:网络
In C#, a common pattern that I use is to populate the details of a lower calculation class with a form object.

In C#, a common pattern that I use is to populate the details of a lower calculation class with a form object.

The constructor for MyForm is:

MyForm()
{
   _MyFormCalcs = new MyFormCalcs(this);
}

But I encountered an error today which makes me think that as my constructor had not finished completing, it creates a new instance of MyForm to pass into MyData. Thus it calls the constructor twice.开发者_开发百科 I found that a static list in MyFormCalcs was being filled twice and was failing the second time as the keys were already present in the list.

Can I use this in the constructor to refer to this instance? What will it contain in the lower class - has the constructor been run or not.

What is a better way of passing my form into the lower class?


No, that won't create a new instance of MyForm.

In general, allowing this to "escape" from a constructor is dangerous as it means it can be used before the constructor has completed, but it's not going to be creating a new instance. If you could give a short but complete example of the problem you've seen, we could help diagnose it further. In particular, it's not clear what you mean about the "static list being filled twice". Usually it's not a good idea to populate a static variable in an instance constructor.


In fact, it is really nice to avoid such call inside constructor, because your object is not already built (constructor hasnt finish its work) but you are already use this "unfinished" object as a parameter. Its a bad way. Good way is creating some special method:

class MyClass
{

 var obj:SomeClass;

  public MyClass()
  {
  }

  public Init()
  {
    obj = SomeClass(this);
  }

}


Make a private property that instantiate MyFormCalcs only when it is first used, like this:

public class MyForm {

  private MyFormCalcs MyFormCalcs {
    get {
      _MyFormCalcs = _MyFormCalcs ?? new MyFormCalcs(this);   
    }
  }
}

This way, you don't have to think about when to "initialize" things.


There is this very complete response of C# constructor order:

C# constructor execution order

0

精彩评论

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

关注公众号