有什么方法可以限制类型变量可能包含的类型吗?

Jon*_*ood 1 .net c# clr types

我的代码类似于以下内容.它将整数与类型相关联.我想然后使用这个字典来查找给定整数的类型,然后实例化该类型.

Dictionary<int, Type> RegistrationMethods;

RegistrationMethods = new Dictionary<int, Type>();
RegistrationMethods.Add(1, typeof(RegistrationProvider_01));
RegistrationMethods.Add(2, typeof(RegistrationProvider_02));
Run Code Online (Sandbox Code Playgroud)

问题:我的所有类型都实现了IRegistrationMethod.有没有办法声明我的字典,以便它只能容纳实现此接口的类型?这将使我的代码更安全.

谢谢你的任何提示.

Lee*_*Lee 6

如果您只想创建它们,您可以:

Dictionary<int, Func<IRegistrationMethod>> RegistrationMethods;
RegistrationMethods.Add(1, () => new RegistrationProvider_01());
Run Code Online (Sandbox Code Playgroud)

或者你可以要求通过一个方法添加所有元素:

public void AddRegistrationMethod<T>(int i) where T : IRegistrationMethod, new()
{
    RegistrationMethods.Add(i, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)