sharing dictionary contents between class instance

2019-07-04 00:37发布

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?

标签: c# scope
1条回答
Emotional °昔
2楼-- · 2019-07-04 01:04

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>();
    }
}
查看更多
登录 后发表回答