你不能完全那样做,这是行不通的。
想象你可以写出以下内容:
public class KeyValuePairs
{
public string Key { get; set; }
public T Value<T> { get; set; }
}
以下代码中foo 变量的类型是什么?
var pair = new KeyValuePairs();
var foo = pair.Value;
好的,现在让我们假设语言允许你这样做:
var pair = new KeyValuePairs();
var foo = pair.Value<int>;
嗯……下面的代码会如何表现?
var pair = new KeyValuePairs();
pair.Value = new Thread();
var foo = pair.Value<int>;
如您所见,语言不允许这样做是有充分理由的。
当然,您可以通过以下方式进行:
public class KeyValuePairs<TValue>
{
public string Key { get; set; }
public TValue Value { get; set; }
}
(或只使用System.Collections.Generic.KeyValuePair<string, TValue>)
或者您可以将属性替换为方法对:
// Warning: bad code!
public class KeyValuePairs<TValue>
{
private object _value;
public string Key { get; set; }
public TValue GetValue<TValue>()
{
return _value;
}
public void SetValue<TValue>(TValue value)
{
_value = value;
}
}
但如果您考虑这样做,显然会遇到设计问题,因为与object-typed 属性相比,这没有任何优势。 p>
这是使用KeyValuePair<string, object>的解决方案:
var list = new List<KeyValuePair<string, object>>();
list.Add(new KeyValuePair<string, object>("string", "Hello, World!"));
list.Add(new KeyValuePair<string, object>("int", 42));
list.Add(new KeyValuePair<string, object>("bool", true));
foreach (var item in list)
Console.WriteLine("[{0}] = {1}", item.Key, item.Value);
这是demo。