[英]C# issue storing objects into Dictionaries
这似乎很简单,但我不确定我做错了什么......
我写了以下 Class,我在Dictionary<string, ClassName>
object 中进一步使用它作为它的.Value
:
public class StorageList
{
static List<int> listForStorage = new();
public void AddToListForStorage(int number)
{
listForStorage.Add(number);
}
public List<int> GetList()
{
return listForStorage;
}
}
当我运行应用程序时,我创建了一个Dictionary<string, StorageList>
并向其中添加了一些元素:
static void Main(string[] args)
{
Dictionary<string, StorageList> dictionary = new();
dictionary.Add("idOne", new StorageList());
dictionary.Add("idTwo", new StorageList());
dictionary["idOne"].AddToListForStorage(1);
dictionary["idOne"].AddToListForStorage(2);
dictionary["idTwo"].AddToListForStorage(3);
dictionary["idTwo"].AddToListForStorage(4);
}
当打印到控制台“idOne”或“idTwo”时,我希望看到“idOne”的 1 和 2,以及“idTwo”的 3 和 4。 但是,我看到 'idOne' 和 'idTwo' 的 1、2、3 和 4...
foreach (var id in dictionary)
{
foreach (var item in dictionary[id.Key].GetList())
{
Console.WriteLine(item);
}
Console.WriteLine($"Finished {id.Key}");
}
// 1
// 2
// 3 <-- Not expected
// 4 <-- Not expected
// Finished idOne
// 1 <-- Not expected
// 2 <-- Not expected
// 3
// 4
// Finished idTwo
对象不同,所以我不太明白为什么会这样。
Console.WriteLine(Object.ReferenceEquals(dictionary["idOne"], dictionary["idTwo"]));
// false
我很感激这方面的一些帮助。 谢谢!
您已将listForStorage
声明为static
,因此它属于StorageList
类型,而不是StorageList
的任何特定实例。
因此,所有StorageList
实例将只使用一个List<int>
实例。
话虽如此,您可能希望将listForStorage
实例变量(删除static
关键字):
public class StorageList
{
List<int> listForStorage = new();
}
现在StorageList
的每个实例都有自己的listForStorage
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.