简体   繁体   中英

Something weird in Visual Studio Debugger

I have some class with private member _stuffs which is of type IStuffs an interface.

When I set a break point just before getting out of the constructor, when debugging and watching the variable at the break point, local variable _stuffs is not null (filled with MyStuffs Object) whereas this._stuffs is null and when back in caller instance MyModelApp._stuffs stays null. Why it is not set with MyStuffs Object ?

public class MyModelApp : ModelApp, IModelApp
{

   private App _parent;

   private IStuffs _stuffs;

   public MyModelApp(object parent)
      : base(parent)
   {
      IStuffs _stuffs = new MyStuffs(this);

      // Break point here
   }    
}

Do you realize you're actually assigning to local variable and not to instance variable?

private IStuffs _stuffs;

public MyModelApp(object parent)
: base(parent)
{
    IStuffs _stuffs = new MyStuffs(this);//This is a local variable

    //If you need local variable also here, just rename it
    //or use this qualifier

    this._stuffs = new MyStuffs(this);
}

Look carefully at your constructor:

public MyModelApp(object parent)
   : base(parent)
{
   IStuffs _stuffs = new MyStuffs(this);
}

You're declaring a local variable called _stuffs and giving it a value. That is not the same as the field _stuffs . I strongly suspect that you don't want a local variable - you just want to initialize the field instead:

public MyModelApp(object parent)
   : base(parent)
{
   _stuffs = new MyStuffs(this);
}

You are creating _stuffs as a new local variable , and not as the private IStuffs _stuffs , which has global scope. I assume you mean to assign new MyStuffs(this); to the global field _stuffs instead of creating an entire new object, because currently you have two different variables , but you are getting confused becaus they have the same name.

private IStuffs _stuffs;

public MyModelApp(object parent)
  : base(parent)
{
   _stuffs = new MyStuffs(this);
} 

The above is the correct way, creating a new MyStuffs object as the variable in the global scope rather than the local scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM