C#中的const字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/853761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
const Dictionary in c#
提问by Samuel Carrijo
I have a class in C# that contains a Dictionary, which I want to create and ensure nothing as added, edited or removed from this dictionary as long as the class which contains it exists.
我在 C# 中有一个包含字典的类,我想创建它并确保只要包含它的类存在,就不会从该字典中添加、编辑或删除任何内容。
readonly doesn't really help, once I tested and saw that I can add items after. Just for instance, I created an example:
readonly 并没有真正帮助,一旦我测试并看到我可以在之后添加项目。举个例子,我创建了一个例子:
public class DictContainer
{
private readonly Dictionary<int, int> myDictionary;
public DictContainer()
{
myDictionary = GetDictionary();
}
private Dictionary<int, int> GetDictionary()
{
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(1, 2);
myDictionary.Add(2, 4);
myDictionary.Add(3, 6);
return myDictionary;
}
public void Add(int key, int value)
{
myDictionary.Add(key, value);
}
}
I want the Add method not to work. If possible, I want it not to even compile. Any suggestions?
我希望 Add 方法不起作用。如果可能,我希望它甚至不编译。有什么建议?
Actually, I'm worried for it is code that will be open for a lot of people to change. So, even if I hide the Add method, it will be possible for someone to "innocently" create a method which add a key, or remove another. I want people to look and know they shouldn't change the dictionary in any ways. Just like I have with a const variable.
实际上,我担心代码会开放给很多人更改。因此,即使我隐藏了 Add 方法,也有可能有人“无辜地”创建一个添加密钥或删除另一个密钥的方法。我希望人们看到并知道他们不应该以任何方式更改字典。就像我有一个 const 变量一样。
采纳答案by Noldorin
There's nothing in the .NET Framework to help you out here, but this postgives a pretty good implementation of a generic ReadOnlyDictionary
in C#. It implements all the interfaces you might expect it to (IDictionary
, ICollection
, IEnumerable
, etc.) and as a bonus, the entire class and its members are fully commented with XML.
.NET Framework 中没有任何内容可以帮助您解决这个问题,但是这篇文章提供了一个很好的ReadOnlyDictionary
C#泛型实现。它实现了您可能期望的所有接口(IDictionary
、ICollection
、IEnumerable
等),而且作为奖励,整个类及其成员都使用 XML 进行了完整的注释。
(I've refrained from posting the code here, because it's really quite long with all the XML comments.)
(我没有在此处发布代码,因为所有 XML 注释真的很长。)
回答by Eoin Campbell
Eh... then don't define the Add Method...
呃...那就不要定义Add方法...
Keep the myDictionary
variable private and expose a Getter/Indexer so that it can only be read from outside that class..
保持myDictionary
变量私有并公开一个 Getter/Indexer,以便它只能从该类之外读取。
wonders if he's completely missing the point
想知道他是否完全没有抓住重点
回答by Neil Barnwell
Hide the Dictionary totally. Just provide a get method on the DictContainer class that retrieves items from the dictionary.
完全隐藏字典。只需在 DictContainer 类上提供一个从字典中检索项目的 get 方法。
public class DictContainer
{
private readonly Dictionary<int, int> myDictionary;
public DictContainer()
{
myDictionary = GetDictionary();
}
private Dictionary<int, int> GetDictionary()
{
Dictionary<int, int> myDictionary = new Dictionary<int, int>();
myDictionary.Add(1, 2);
myDictionary.Add(2, 4);
myDictionary.Add(3, 6);
return myDictionary;
}
public this[int key]
{
return myDictionary[key];
}
}
回答by arul
There's no built-in way to do that, consider using a wrapper class.
没有内置的方法可以做到这一点,请考虑使用包装类。
回答by Tolgahan Albayrak
interface IReadOnlyDic<Key, Value>
{
void Add(Key key, Value value);
}
class ReadOnlyDic<Key, Value> : Dictionary<Key, Value>, IReadOnlyDic<Key, Value>
{
public new void Add(Key key, Value value)
{
//throw an exception or do nothing
}
#region IReadOnlyDic<Key,Value> Members
void IReadOnlyDic<Key, Value>.Add(Key key, Value value)
{
base.Add(key, value);
}
#endregion
}
to add custom items;
添加自定义项目;
IReadOnlyDic<int, int> dict = myDictInstance as IReadOnlyDic<int, int>;
if (dict != null)
dict.Add(1, 155);
回答by Tolgahan Albayrak
and this is another way
这是另一种方式
class ReadOnlyDic<Key, Value> : Dictionary<Key, Value>
{
private bool _locked = false;
public new void Add(Key key, Value value)
{
if (!_locked)
{
base.Add(key, value);
}
else
{
throw new ReadOnlyException();
}
}
public void Lock()
{
_locked = true;
}
}
回答by Samuel Carrijo
I liked the linkfrom bruno-conde, which was a simpler one, but once I can't mark his comment as the answer, I'll mark Noldorinanswer as the official, for it is a similar and satisfying answer.
我喜欢来自bruno-conde的链接,这是一个更简单的链接,但是一旦我无法将他的评论标记为答案,我会将Noldorin 的答案标记为官方答案,因为这是一个相似且令人满意的答案。
Too bad there's not a way to prevent the code from compiling :(. Thanks, guys
太糟糕了,没有办法阻止代码编译:(。谢谢,伙计们
回答by SoftwareRockstar
Here's a better alternative as I have described at:
这是我在以下位置描述的更好的选择:
http://www.softwarerockstar.com/2010/10/..
http://www.softwarerockstar.com/2010/10/..
Essentially it's a much simpler solution subclassing ReadOnlyCollection, which gets the work done in a more elegant manner.
本质上,它是一个更简单的解决方案,它继承了 ReadOnlyCollection,以更优雅的方式完成工作。
回答by batbaatar
FYI, now it is built-in to .net 4.5.
仅供参考,现在它内置于 .net 4.5。
http://msdn.microsoft.com/en-us/library/gg712875(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/gg712875(v=vs.110).aspx