[英]Something weird in Visual Studio Debugger
我有一些带有私有成员_stuffs的类,其类型为IStuffs接口。
当我刚好退出构造函数之前设置断点时,调试并在断点处查看变量时,局部变量_stuffs不为null(填充有MyStuffs对象),而this._stuffs为null且返回调用方实例MyModelApp时._stuffs保持为空。 为什么未使用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
}
}
您是否意识到您实际上是在分配给局部变量而不是实例变量?
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);
}
仔细查看您的构造函数:
public MyModelApp(object parent)
: base(parent)
{
IStuffs _stuffs = new MyStuffs(this);
}
您正在声明一个名为_stuffs
的局部变量 ,并为其指定一个值。 这是不一样的领域_stuffs
。 我强烈怀疑您不需要局部变量-您只想初始化字段:
public MyModelApp(object parent)
: base(parent)
{
_stuffs = new MyStuffs(this);
}
您正在创建_stuffs
作为新的局部变量 ,而不是将其创建为具有全局范围的private IStuffs _stuffs
。 我假设您是要分配new MyStuffs(this);
到全局字段_stuffs
而不是创建一个完整的新对象,因为当前您有两个不同的变量 ,但是由于它们具有相同的名称而感到困惑。
private IStuffs _stuffs;
public MyModelApp(object parent)
: base(parent)
{
_stuffs = new MyStuffs(this);
}
上面是正确的方法,在全局作用域而不是本地作用域中创建一个新的MyStuffs
对象作为变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.