C# 字典值引用类型 - 请解释为什么会这样

标签 c# dictionary pass-by-reference

我不明白以下 C# 中的 linqpad 查询的结果。评论应该解释我感到困惑的地方。

void Main()
{
    Dictionary<string, testClass> test = new Dictionary<string, testClass>();

    string key = "key";
    testClass val = null;

    test.Add(key, val);

    val = new testClass();

    test[key].Dump(); //returns null.   WHAT? I just set it!!!



    test[key] = val;
    val.Text = "something";
    //  returns val object, with Text set to "Something". 
    //  If the above didn't work, why does this work?
    test[key].Dump(); 



    val.Text = "Nothing";
    //  return val object, with Text set to "Nothing". 
    //  This, I expect, but, again, why didn't the first example work?
    test[key].Dump(); 



    val = null;
    //  returns val object, with Text set to "Nothing"...WHAT?? 
    //  Now my head is going to explode...
    test[key].Dump(); 

}

// Define other methods and classes here

public class testClass
{
    public override string ToString()
    {
        return Text;
    }

    public string Text { get; set;}     
}

最佳答案

主要原因是变量(val)不是对象。它仅包含对对象(或 null)的引用。

testClass val = null 声明类型为 testClass 的变量并将其设置为 null。它不指向任何对象。

test.Add(key, val) 在字典中添加一个指向 null 的条目(注意:它指向val 也不指向任何对象)。

val = new testClass(); 创建 testClassnew 实例,val 现在指向它新对象。 test[key] 仍然是 null 并且没有指向任何对象。

test[key] = val;
val.Text = "something";
test[key].Dump(); 

此代码将 test[key] 指向 val 指向的同一对象。再次注意它没有指向val。当您使用 val.Text = "something" 更改对象时,您可以使用 test[key].Dump() 查看更改,因为它们都指向同一个对象。

val.Text = "Nothing";
test[key].Dump(); 

当您将 val.Text 设置为字符串“Nothing”时,出于与上述相同的原因,您可以通过 test[key] 看到更改,它们都指向同一个对象

val = null;
test[key].Dump(); 

此代码将 val 设置为指向 null。 test[key] 仍然 指向对象。现在 valtest[key] 指向不同的东西。

关于C# 字典值引用类型 - 请解释为什么会这样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225847/

相关文章:

c# - 通过 ref 和 out

c# - Async MethodInfo Invoke - 动态转换返回类型

c# - 命名空间 'Management' 中不存在类型或命名空间名称 'MicrosoftSqlServer' 您是否缺少程序集引用

swift - 删除单元格时的字典值 - 在展开可选值时意外发现 nil

python - 从具有字典键的另一列创建 Pandas 数据框列

c++ - 在不先插入标准 map 元素的情况下调用函数

c# - 我应该在这里使用 ref 还是 out 关键字?

c# - 如何从基类中获取自定义属性?

c# - 单例 - 我可以创建多个实例

JavaScript - 替换对象中的数组值