当我们使用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
).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.