问题
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