简体   繁体   English

Visual Studio调试器中有些奇怪的东西

[英]Something weird in Visual Studio Debugger

I have some class with private member _stuffs which is of type IStuffs an interface. 我有一些带有私有成员_stuffs的类,其类型为IStuffs接口。

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. 当我刚好退出构造函数之前设置断点时,调试并在断点处查看变量时,局部变量_stuffs不为null(填充有MyStuffs对象),而this._stuffs为null且返回调用方实例MyModelApp时._stuffs保持为空。 Why it is not set with MyStuffs Object ? 为什么未使用MyStuffs对象设置它?

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. 您正在声明一个名为_stuffs局部变量 ,并为其指定一个值。 That is not the same as the field _stuffs . 这是一样的领域_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. 您正在创建_stuffs作为新的局部变量 ,而不是将其创建为具有全局范围的private IStuffs _stuffs I assume you mean to assign new MyStuffs(this); 我假设您是要分配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. 到全局字段_stuffs而不是创建一个完整的新对象,因为当前您有两个不同的变量 ,但是由于它们具有相同的名称而感到困惑。

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. 上面是正确的方法,在全局作用域而不是本地作用域中创建一个新的MyStuffs对象作为变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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