我有这样的课程:
static private Dictionary<int, String> states;
static public Dictionary<int, String> GetStates()
{
if (states != null)
{
return states;
}
else
{
states = new Dictionary<int, string>();
states.Add(1, "State 1 name.");
states.Add(2, "State 2 name");
// etc
}
return states;
}
返回的字典应该是不可修改的。 寻找解决此问题的最佳方法。
答案 0 :(得分:2)
如果您将退货类型更改为IDictionary<TKey, TValue>
,那么您应该能够返回ReadOnlyDictionary
:
static public IDictionary<int, String> GetStates()
{
if (states != null)
{
return new ReadOnlyDictionary(states);
}