首页 > 解决方案 > Declare a List of class references

问题描述

I need to declare a list of class references. Specifically, a list of classes which implement a interface which here I'll call IInterface.

Similar to how List can be a list of types and look like this:

List<Type> types = new List<Type> {string, bool, int, float};

I need to accomplish the same thing, where each of those are my own classes and implement the interface IInterface so:

List<(idk)> references = new List<(idk)> {myClass, myClass2, myClass3};

and all of them are MyClass : IInterface, MyClass2 : IInterface and MyClass3 : IInterface.

I need this so that when I create and instance of the type, the compiler will know that the type implements IInterface.

标签: c#reflectioncollections

解决方案


如果您基本上想要一个List<Type>需要Types 来实现接口的地方,并且您希望在编译时强制执行,这实际上可以通过包装List<Type>并使 add 方法具有受约束的泛型类型参数并使用它添加到列表中,但使用起来可能有点笨拙(您将无法使用您在问题中提到的漂亮的集合初始值设定项语法):

public class TypeList<T> : IEnumerable<Type>
{
    private List<Type> _list = new List<Type>();

    public void Add<TAdd>() where TAdd : T
    {
        _list.Add(typeof(TAdd));
    }

    public IEnumerator<Type> GetEnumerator() => _list.GetEnumerator();

    IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator();
}

此类的泛型类型参数是您希望列表约束的类型,因此在您的示例中,使用列表如下所示:

var list = new TypeList<IInterface>();
list.Add<MyClass>();
list.Add<MyClass2>();
list.Add<MyClass3>();

这些将无法编译:

list.Add<string>();
list.Add<bool>();
list.Add<int>();
list.Add<float>();

推荐阅读