2

我有一个类,我有一个字典,其中包含一个特定的键。但价值应该是通用的。

就像是:

private Dictionary<String,TValue> _Dictionary;

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

4

2 回答 2

2

所以你想要一个通用字典?使用预定义的类。

public Dictionary<int, string> _dictionary = new Dictionary<int, string>();

这为您提供了一个带有整数键和字符串值的字典。如果您需要一个只有其中一个变量的 Dictionary,您可以继承 Dictionary 来创建自己的类型。

public class KeyTypeConstantDictionary<T> : Dictionary<int, T>
{
}

然后使用它是这样的:

KeyTypeConstantDictionary<string> x = new KeyTypeConstantDictonary<string>();
// Equivalent to Dictionary<int, string>()
KeyTypeConstantDictionary<SomeObject> x = new KeyTypeConstantDictonary<SomeObject>();
// Equivalent to Dictionary<int, SomeObject>()

希望我正确理解了您的问题。

于 2011-03-16T20:56:22.460 回答
2

如果您在泛型类型中使用它,Tejs 的答案是合适的。

但是,如果您只是尝试使用固定类型的键创建字典,但可以存储任何值,则一种选择是仅System.Object用于您的值:

 private Dictionary<string, object> _dictionary;

这将允许您将任何对象分配给该值。但是,这有潜在的危险,因为您会失去类型安全性并且需要确保正确拆箱和转换对象。

于 2011-03-16T20:58:22.340 回答