[英]C# Get from Hashtable, get object or reference
当我们使用key从Hashtable获取一个对象时,我们得到一个引用的对象,即如果我们更改类的属性会影响Hashtable中的对象吗?
That will depend on whether the object is a reference or a value type. 这将取决于对象是引用还是值类型。 Example: 例:
public class Foo
{
public string Bar { get; set; }
}
public struct Baz
{
public string Bazinga { get; set; }
}
class Program
{
static void Main()
{
var hashtable1 = new Dictionary<string, Foo>
{
{ "key1", new Foo { Bar = "old bar" } }
};
var hashtable2 = new Dictionary<string, Baz>
{
{ "key1", new Baz { Bazinga = "old bazinga" } }
};
var foo = hashtable1["key1"];
foo.Bar = "new bar";
var bar = hashtable2["key1"];
bar.Bazinga = "new bazinga";
Console.WriteLine(hashtable1["key1"].Bar);
Console.WriteLine(hashtable2["key1"].Bazinga);
}
}
prints: 打印:
new bar
old bazinga
Yes, if your object is a reference type ( class
, not struct
). 是的,如果您的对象是引用类型( class
,而不是struct
)。
Here is some code that proves it: 以下是一些证明它的代码:
var ht = new Hashtable();
var o = new object();
ht["key"] = o;
Console.WriteLine(object.ReferenceEquals(o, ht["key"])); // == true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.