简体   繁体   English

C# 问题将对象存储到字典中

[英]C# issue storing objects into Dictionaries

This seems to be simple, but I'm not sure what I'm doing wrong...这似乎很简单,但我不确定我做错了什么......

I wrote the following Class, which I further use it in a Dictionary<string, ClassName> object, as its .Value :我写了以下 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;
    }
}

When I run the application, I create a Dictionary<string, StorageList> and add a few elements to it:当我运行应用程序时,我创建了一个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);
}

When printing to the console either 'idOne' or 'idTwo', I was expecting to see 1 and 2 for 'idOne' and 3 and 4 for 'idTwo.当打印到控制台“idOne”或“idTwo”时,我希望看到“idOne”的 1 和 2,以及“idTwo”的 3 和 4。 However, I see 1, 2, 3 and 4 for both 'idOne' and 'idTwo'...但是,我看到 '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

Objects are different, so I don't quite understand why this is happening.对象不同,所以我不太明白为什么会这样。

Console.WriteLine(Object.ReferenceEquals(dictionary["idOne"], dictionary["idTwo"]));
// false

I'd appreciate some assistance on this.我很感激这方面的一些帮助。 Thanks!谢谢!

You have declared listForStorage as static , so it belongs to the StorageList type rather than any specific instance of StorageList .您已将listForStorage声明为static ,因此它属于StorageList类型,而不是StorageList的任何特定实例。

Consequentially, there will be only one List<int> instance used by all instances of StorageList .因此,所有StorageList实例将只使用一个List<int>实例。

That being said, you probably want to make listForStorage an instance variable (remove the static keyword):话虽如此,您可能希望将listForStorage实例变量(删除static关键字):

public class StorageList
{
    List<int> listForStorage = new();
}

Now each instance of StorageList will have its own listForStorage .现在StorageList的每个实例都有自己的listForStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM