c# - 从实异常(exception)部将属性设置为 null

标签 c# .net

我发现了以下我很难理解的行为。

我假设您可以将对象 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 之前:

Before the change

在你分配 child = null 之后:

After the change

这就是为什么

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/

相关文章:

c# - DependencyProperties 未按预期在 UserControl 中触发回调

c# - Azure Blob 容器名称可以有多长?

c# - Amazon S3 PutObject() 返回值确认成功?

.net - 链接 .Net 程序集

c# - 在Azure服务器中每天自动调用一次API

c# - 为什么 MemoryStream 不提供采用 "long"容量的构造函数?

c# - 我怎样才能使这段代码更优化

c# - 允许使用 HttpClient 的不受信任的 SSL 证书

c# - 是否使用泛型?

c# - 原始 H264 到 JPEG,在 C# 中