您编写什么代码来约束名为MyDictionary具有引用类型值的值类型键的通用字典?
我想这是我的答案:
public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{
}
但我不确定这是否是正确的答案..
您编写什么代码来约束名为MyDictionary具有引用类型值的值类型键的通用字典?
我想这是我的答案:
public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{
}
但我不确定这是否是正确的答案..
Looks fine to me. One small caveat, you won't be able to use Nullable types (e.g. int?) as either keys or values in such a dictionary.
From Constraints on Type Parameters:
where T: structThe type argument must be a value type. Any value type exceptNullablecan be specified.
where T: classThe type argument must be a reference type; this applies also to any class, interface, delegate, or array type.
没问题。如果会很好。
var c = new Dictionary<MyStruct?, MyClass>();
MyStruct? key = new MyStruct(){ X =5};
var value = new MyClass();
c.Add(key, value);
Console.WriteLine(c[key].Prop);