如何创建通用词典?
我有一堂课,其中有一本持有特定键的字典。但值应该是通用的。
比如:
private Dictionary<String,TValue> _Dictionary;
但是 TValue 没有找到(显然),但是我还应该输入什么?我找到了 IList 的解决方案,但我只想添加一个通用对象。
I have a Class where i have a Dictionary holding a specific Key. But the Value should be generic.
Something like:
private Dictionary<String,TValue> _Dictionary;
But TValue is not found (obvesly) but what else should i put in? I found a solution for IList but i just want to add one Generic Object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那么你想要一本通用词典吗?使用预定义的类。
这将为您提供一个带有整数键和字符串值的字典。如果您需要一个只有其中一个变量的 Dictionary,您可以继承 Dictionary 来创建您自己的类型。
然后使用它就像这样:
希望我正确理解你的问题。
So you want a generic dictionary? Use the pre defined class.
That gives you a dictionary with an integer key, and a string value. If you need a Dictionary with only one of those being variable, you can inherit Dictionary to make your own type.
Then using it is like so:
Hopefully I understood your question correctly.
如果您在泛型类型中使用它,Tejs 答案 是合适的。
但是,如果您只是尝试创建一个具有固定类型键但可以存储任何值的字典,则一种选择是仅使用
System.Object
作为您的值:这将允许您将任何对象分配给值。但是,这存在潜在危险,因为您会失去类型安全性,并且需要确保正确拆箱并转换对象。
If you're using this within a generic type, Tejs answer is appropriate.
However, if you're just trying to make a dictionary with a fixed type of key, but which can store any value, one option is to just use
System.Object
for your value:This will allow you to assign any object into the value. However, this is potentially dangerous, as you lose type safety and need to make sure to unbox and convert the object correctly.