3

您编写什么代码来约束名为MyDictionary具有引用类型值的值类型键的通用字典?

我想这是我的答案:

public class MyDictionary<Tkey,TValue>:Dictionary<Tkey,TValue>
where Tkey:struct
where TValue:class
{

}

但我不确定这是否是正确的答案..

4

2 回答 2

4

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: struct The type argument must be a value type. Any value type except Nullable can be specified.

where T: class The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

于 2012-10-08T00:31:40.610 回答
0

没问题。如果会很好。

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);
于 2021-06-12T07:15:52.590 回答