开发者

How can I prevent outside code to manipulate contents of the Dictionary?

I want a Dictionary<string, string> property which should not be changed/set by the outside code. To achieve this, I can declare private variable and it's property with get accessor only.

e.g.

private static Dictionary<string, string> myDic = new Dictionary <string, string>();
     Public static Dictionary<string, string> MyDictionary
     {
          get开发者_JAVA技巧 { return myDic;}
     }

But in this case, outside code can manipulate 'contents' of the dictionary. e.g. MYClass.MyDictionary["FirstSampleKey"] = "Replacing original value by New Value";

I dont want any outside code to manipulate contents of the dictionary. How can I achieve this?


I don't believe there is a read only dictionary (which would be nice as there is a ReadOnlyCollection). Your best bet would probably be to not expose the dictionary at all and expose properties/methods that allow the developer to get at the information without allowing them to directly access the dictionary.

If this is something you will be doing a lot of, you can look into either using someone else's ReadOnlyDictionary implementation (there are plenty out there if you Google it), or you can write your own.


I would also say that you could write a method for the developers to look up their words, or else you could return a copy of the dictionary, this way the dictionary works as it do now, but of cause you would have to copy the dictionary every time the get method is called which could take some time if it's a large dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜