我发现了以下我很难理解的行为。
我假设您可以将对象 A 的属性设置为对象 B,操作对象 B,并且更改将继续到对象 A 的属性(因为它是同一个对象)。我期待这个单元测试能够通过,但是当将 B 设置为 null 时它在最后一行失败了。为什么?
[TestMethod]
public void TestObject()
{
Child child = new Child();
var parent = new Parent(child);
child.Name = "John";
Assert.AreEqual(parent.Child.Name, "John");
child = null;
Assert.IsNull(parent.Child);
}
public class Child
{
public string Name { get; set; }
}
public class Parent
{
public Child Child { get; set; }
public Parent(Child kid)
{
Child = kid;
}
}
最佳答案
这一行
child = null;
并没有按照您的想法行事。它取消了对 TestObject()
方法持有的 Child
对象的引用,但它对对同一 Child
的引用没有影响Parent
对象持有的对象:
在分配 child = null
之前:
在你分配 child = null
之后:
这就是为什么
Assert.IsNull(parent.Child);
失败:parent.Child
引用与您已取消的 child
引用不同。
另一方面,如果您执行 child.Name = null
,那么 parent.Child.Name
也会变成 null
:
child.Name = null;
Assert.IsNull(parent.Child.Name);
关于c# - 从实异常(exception)部将属性设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433109/