如何重载 [] 运算符?

发布于 2024-09-01 20:26:22 字数 224 浏览 3 评论 0原文

我正在创建一个类,该类将字典作为私有成员填充。我想公开字典的值而不公开字典本身(以只读方式)。我可以轻松地创建一个属性来公开 _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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暗恋未遂 2024-09-08 20:26:23

我很确定这就是您想要的:

public TValue this[TKey key] {
    get { return _dictionary[key]; }
}

如果您想实现一个接口来向客户端代码指示您的类可以通过 TKey 类型的索引访问,最接近的匹配(即我知道)是 IDictionary

不幸的是,IDictionary 有一大堆违反您的只读要求的成员,这意味着您必须显式实现大量成员才能抛出 NotImplementedException code> (或类似的),当它们被调用时:即 thisAddClearRemove< 的 setter /代码>。

也许有一个不同的接口更适合此目的(例如 IReadOnlyDictionary?);我只是还没遇到过。

当然,如果您打算拥有多个提供与此类似的功能的类,您也可以编写自己的接口。

I'm pretty sure this is what you're after:

public TValue this[TKey key] {
    get { return _dictionary[key]; }
}

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) is IDictionary<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 a NotImplementedException (or somesuch) when they're called: namely, the setter for this, Add, Clear, and Remove.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文