字典 - 使用类型作为键并将其约束为仅限于某些类型

Mam*_*ate 3 c# generics dictionary

如果我们使用Type作为字典的键,是否可以将该类型仅限制为特定类型?例如:

public abstract class Base
{ }

public class InheritedObject1 : Base
{ }

public class InheritedObject2 : Base
{ }

public class Program
{
    public Dictionary<Type, string> myDictionary = new Dictionary<Type, string>();
}
Run Code Online (Sandbox Code Playgroud)

因此,从上面给出的代码中我想将Type仅限制为:Base和从中继承的每个类.有可能做出这样的约束吗?

Mar*_*tin 8

只需创建一个继承自的模板类Dictionary,如下所示:

class CustomDictionary<T> : Dictionary<T, string>
    where T : Base
{
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据需要在代码中使用它:

    public void Test()
    {
        CustomDictionary<InheritedObject1> Dict = new CustomDictionary<InheritedObject1>();

        Dict.Add(new InheritedObject1(), "value1");
        Dict.Add(new InheritedObject1(), "value2");
    }
Run Code Online (Sandbox Code Playgroud)