如何重载 [] 运算符?
我正在创建一个类,该类将字典作为私有成员填充。我想公开字典的值而不公开字典本身(以只读方式)。我可以轻松地创建一个属性来公开 _dictionary.Keys
,但是如何重载 []
以便 MyClass[key]
返回 _dictionary[key]
?
我想我可能需要实现一个接口,但我不确定是哪一个......
I'm creating a class which populates a dictionary as a private member. I want to expose the values of the dictionary without exposing the dictionary itself (in a read-only fashion.) I can easily make a property to expose _dictionary.Keys
, but how can I overload []
so that MyClass[key]
returns _dictionary[key]
?
I think I may need to implement an interface, but I'm not sure which one...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我很确定这就是您想要的:
如果您想实现一个接口来向客户端代码指示您的类可以通过
TKey
类型的索引访问,最接近的匹配(即我知道)是IDictionary
。不幸的是,
IDictionary
有一大堆违反您的只读要求的成员,这意味着您必须显式实现大量成员才能抛出NotImplementedException
code> (或类似的),当它们被调用时:即this
、Add
、Clear
和Remove< 的 setter /代码>。
也许有一个不同的接口更适合此目的(例如
IReadOnlyDictionary
?);我只是还没遇到过。当然,如果您打算拥有多个提供与此类似的功能的类,您也可以编写自己的接口。
I'm pretty sure this is what you're after:
If you want to implement an interface to indicate to client code that your class can be accessed by an index of type
TKey
, the closest match (that I'm aware of) isIDictionary<TKey, TValue>
.Unfortunately,
IDictionary<TKey, TValue>
has a whole bunch of members that violate your read-only requirement, which means you would have to explicitly implement lots of members only to throw aNotImplementedException
(or somesuch) when they're called: namely, the setter forthis
,Add
,Clear
, andRemove
.Maybe there's a different interface that would be more appropriate for this purpose (something like
IReadOnlyDictionary<TKey, TValue>
?); I just haven't come across it.You could also write your own interface, of course, if you intend to have multiple classes that offer functionality similar to this.
这称为索引器。请参阅 http://msdn.microsoft.com/en-us/library/2549tw02 .aspx
This is called an Indexer. See http://msdn.microsoft.com/en-us/library/2549tw02.aspx