C# 如何创建通用词典?

C# 如何创建通用词典?,c#,generic-programming,C#,Generic Programming,我有一个类,我有一本字典,里面有一个特定的键。但该值应该是通用的 比如: private Dictionary<String,TValue> _Dictionary; private Dictionary\u Dictionary; 但是没有找到TValue(显然),但是我还应该在其中添加什么呢?我找到了IList的解决方案,但我只想添加一个通用对象。那么你想要一个通用字典?使用预定义的类 public Dictionary<int, string> _diction

我有一个类,我有一本字典,里面有一个特定的键。但该值应该是通用的

比如:

private Dictionary<String,TValue> _Dictionary;
private Dictionary\u Dictionary;

但是没有找到TValue(显然),但是我还应该在其中添加什么呢?我找到了IList的解决方案,但我只想添加一个通用对象。

那么你想要一个通用字典?使用预定义的类

public Dictionary<int, string> _dictionary = new Dictionary<int, string>();
public Dictionary\u Dictionary=new Dictionary();
这将为您提供一个带有整型键和字符串值的字典。如果您需要一个只有一个变量的字典,您可以继承字典来创建自己的类型

public class KeyTypeConstantDictionary<T> : Dictionary<int, T>
{
}
公共类KeyTypeConstantDictionary:字典
{
}
然后使用它就像这样:

KeyTypeConstantDictionary<string> x = new KeyTypeConstantDictonary<string>();
// Equivalent to Dictionary<int, string>()
KeyTypeConstantDictionary<SomeObject> x = new KeyTypeConstantDictonary<SomeObject>();
// Equivalent to Dictionary<int, SomeObject>()
KeyTypeConstantDictionary x=新的KeyTypeConstantDictionary();
//相当于字典()
KeyTypeConstantDictionary x=新的KeyTypeConstantDictionary();
//相当于字典()

希望我正确理解了你的问题

如果您在泛型类型中使用此选项,则是适当的

但是,如果您只是尝试使用固定类型的键制作一个字典,但它可以存储任何值,那么一个选项就是仅使用
System.Object
作为您的值:

 private Dictionary<string, object> _dictionary;
private Dictionary\u Dictionary;

这将允许您将任何对象指定给该值。但是,这有潜在的危险,因为您失去了类型安全性,需要确保正确取消装箱和转换对象。

这将在哪里使用?另外,为值选择对象类型并不会比System.Collections.Hashtable好多少=D@Tejs:这取决于你的目标是什么-你计划在价值中存储什么?这将帮助我们确定最好的选择是什么。。。