sharing dictionary contents between class instances

丶灬走出姿态 提交于 2019-12-10 21:56:26

问题


let's say I have a Dictionary structure like

var stocks = new Dictionary<string, double>();
stocks.Add("APPL", 1234.56);

While retaining the ability to Add and Remove from the Dictionary, is there a way the contents can be 'shared' between instances of it's containing class? (By the way, I am forced to inherit from a containing class that cannot be static.)

Or is there another way to represent the data that would allow this type of sharing?


回答1:


A class does not need to be static to have static members. I would recommend having the dictionary as a protected static property. Also for thread safety you need to use the ConcurrentDictionary rather than the normal Dictionary

public class MyClass
{
    protected static ConcurrentDictionary<string, double> Stocks {get; set;} 

    static MyClass()
    {
        Stocks = new ConcurrentDictionary<string, double>();
    }
}


来源:https://stackoverflow.com/questions/13057960/sharing-dictionary-contents-between-class-instances

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!