我的问题是,由于字符串的行为方式类似于值类型,是否最终会重复字典中保存的字符串?
C#中的字符串不是值类型,它们当然不会像一个类似的行为。
C#字符串是不可变的,这使得它们适合用作关联容器中的键。但是,使用字符串作为关键字或以任何其他身份使用,不会导致克隆其内容。
您可以通过检查源数组的SomeStringProperty
的字典关键字的引用相等性来验证是否正在进行克隆。字典中的每个键将存在于源阵列中:
var data = new[] {
new Something {SomeIntProperty=1, SomeStringProperty="A"}
, new Something {SomeIntProperty=2, SomeStringProperty="A"}
, new Something {SomeIntProperty=3, SomeStringProperty="A"}
, new Something {SomeIntProperty=4, SomeStringProperty="A"}
, new Something {SomeIntProperty=5, SomeStringProperty="A"}
, new Something {SomeIntProperty=6, SomeStringProperty="B"}
, new Something {SomeIntProperty=7, SomeStringProperty="B"}
, new Something {SomeIntProperty=8, SomeStringProperty="C"}
, new Something {SomeIntProperty=9, SomeStringProperty="D"}
};
var dict = data.GroupBy(s => s.SomeStringProperty)
.ToDictionary(g => g.Key);
foreach (var key in dict.Keys) {
if (data.Any(s => ReferenceEquals(s.SomeStringProperty, key))) {
Console.WriteLine("Key '{0}' is present.", key);
} else {
Console.WriteLine("Key '{0}' is not present.", key);
}
}
上述代码打印
Key 'A' is present.
Key 'B' is present.
Key 'C' is present.
Key 'D' is present.
Demo.
很简洁的解释。另请参阅:[这个答案](https://stackoverflow.com/questions/10792603/how-are-strings-passed-in-net) –