我发现了一个非常令人困惑的行为:
我有两个for
块。我在每个对象中声明了两个具有相同名称newDevice
的不同对象。我希望第一个for
块结束时第一个对象超出范围,而第二个for
块中创建一个新对象。
实际发生的是,初始值永远不会被释放"来自变量名称。变量名仍引用第一个对象。
编译器不会抱怨已经声明的对象,如果我没有在第二个属性中使用var
关键字,则"无法解析符号"出现错误。
以下是简化代码:
/* First "for" loop */
var masters = networkDiscoveryCompletedEventArgs.ConnectionInfos.Where(x => x.DataModelHandshake.DeviceId == masterId).ToList();
foreach (var connectionInfoMaster in masters)
{
// First declaration. newDevice's type, after construction, is "MasterDevice".
var newDevice = new MasterDevice
{
DeviceName = connectionInfoMaster.DataModelHandshake.Name,
DeviceId = connectionInfoMaster.DataModelHandshake.DeviceId,
ConnectionInfo = connectionInfoMaster
};
MasterDevices.Add(newDevice);
}
/* Second "for" loop */
var slaves = networkDiscoveryCompletedEventArgs.ConnectionInfos.Where(x => x.DataModelHandshake.DeviceId != masterId).ToList();
foreach (var connectionInfoSlave in slaves)
{
// Second declaration. Inspecting newDevice in debbug mode,
// it's not undeclared at this point. Instead, it retains
// the previous object reference ("MasterDevice"). newDevice's type, after construction,
// is also "MasterDevice".
var newDevice = new SlaveDevice
{
DeviceName = connectionInfoSlave.DataModelHandshake.Name,
DeviceId = connectionInfoSlave.DataModelHandshake.DeviceId,
ConnectionInfo = connectionInfoSlave
};
SlaveDevices.Add(newDevice);
}
使用不同的名称解决了这个问题。
我错过了什么,还是编译错误?
这从未发生过,我真的很困惑。