我不明白以下 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();
创建 testClass
的 new 实例,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]
仍然 指向对象。现在 val
和 test[key]
指向不同的东西。
关于C# 字典值引用类型 - 请解释为什么会这样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36225847/