C# 4.0 中字典元素的 getter
我想实现一个字典,仅在访问它们时(而不是提前)动态创建自己的元素。为此,我想使用 getter 方法,但我根本找不到任何有关如何在字典元素上下文中声明 getter 的信息。
我确实了解如何向整个字典添加一个 getter(调用时必须返回一个字典),但我想要做的是实现一个 getter,当访问字典中的单个元素时调用该 getter,以便我可以创建该元素在飞行中。该 getter 必须接收用于请求的密钥作为参数,并且必须返回相应的值。
我在文档中没有找到该任务的任何语法。
I want to implement a dictionary that creates its own elements on the fly only when they are accessed (not in advance). To do that I would like to use a getter method, but I simply don't find any information how to declare a getter in the context of dictionary elements.
I do understand how to add a getter to the whole dictionary (which must return a dictionary when called), but what I want to do is implement a getter that is called when a single element in the dictionary is accessed so I can create that element on the fly. That getter must receive the key that is used for the request as a parameter and it must return the corresponding value.
I do not find any syntax for that task in the docs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需要在
Dictionary<,>
上重新实现索引器。如果您需要更复杂的值实例化,则可以使用激活器函数
用法:
You just need to reimplement the indexer on
Dictionary<,>
If you need a more sophisticated value instantiation, you can use an activator function
Usage:
虽然 Kev 的答案是完全正确的,并且是在专业水平上给出的,但它仍然给我带来了困难(并启动了很多富有成效的学习 - 感谢 Kev!)。正如您所知,我是 C# 的学习者,有许多概念我仍然需要吸收。我想在这里添加我自己的问题的答案,以防其他人遇到同样的问题并且与我的理解水平相似。也许这会节省一些生命。
Kev 在他的回答中使用了泛型——这是 C#2 中引入的一个很棒的概念。为了简化答案,我想在没有泛型的情况下显示它,并添加大量注释,这些注释给出了我必须查找的所有概念的提示(并且部分不容易找到):
While the answer of Kev is perfectly correct and given on a professional level it still gave me a hard time (and initiated a lot of fruitful learning - thanks Kev!). As you can tell I am a learner of C# and there are many concepts that I still have to assimilate. I want to add an answer to my own question here in case anybody else has the same problem and is on a similar level of understanding as me. Maybe this will save some livetime.
Kev used Generics in his answer - a great concept introduced with C#2. To simplify the answer I want to show it without Generics and with a lot of comments added that give hints to all concepts that I had to look up (and that were partially not easy to find):
它已经在框架中实现了。如果您致电,
您的字典将填充键值对 <1,“Hello”>,<2,“World!”> 等。
It's already implemented in the framework. If you call
you will have your dictionary populated with the key-value pairs <1, "Hello">, <2, "World!">