简体   繁体   English

在C#中创建类型列表

[英]Create a list of types in C#

I'd like to create a list of types, each of which must implement a particular interface. 我想创建一个类型列表,每个类型都必须实现一个特定的接口。 Like: 喜欢:

interface IBase { }
interface IDerived1 : IBase { }
interface IDerived2 : IBase { }

class HasATypeList
{
    List<typeof(IBase)> items;
    HasATypeList()
    {
        items.Add(typeof(IDerived1));
    }

}

So I know I can do 所以我知道我能做到

List<Type> items;

But that won't limit the allowable types in the list to ones that implement IBase. 但是,这不会将列表中允许的类型限制为实现IBase的类型。 Do I have to write my own list class? 我是否必须编写自己的列表类? Not that it's a big deal, but if I don't have to... 不是说这是一个大问题,但如果我不需要......

typeof(IBase) , typeof(object) , typeof(Foo) , all return an instance of Type , with the same members and so on. typeof(IBase)typeof(object)typeof(Foo) ,都返回Type的实例,具有相同的成员,依此类推。

I don't see what you're trying to achieve and why you want to make a distinction between those ? 我不知道你想要实现的目标以及为什么要区分它们?

In fact, the code you're writing here: 事实上,你在这里写的代码:

List<typeof(IBase)> items;

(i don't even know if this compiles ? ) Is exactly the same as this: (我甚至不知道这是否编译?)与此完全相同:

List<Type> items;

So in fact, what you're trying to achieve is imho useless. 所以事实上,你想要实现的目标是无用的。

If you really want to achieve this -but I do not see why ... -, you can always create your own collection-type like Olivier Jacot-Descombes is suggesting, but in that case, I'd rather create a type that inherits from Collection<T> instead: 如果你真的想要实现这个目标 - 但是我不明白为什么...... - 你总是可以创建自己的集合类型,就像Olivier Jacot-Descombes所暗示的那样,但在这种情况下,我宁愿创建一个继承的类型来自Collection<T>

public class MyTypeList<T> : Collection<Type>
{
    protected override InsertItem( int index, Type item )
    {
        if( !typeof(T).IsAssignableFrom(item) )
        {
            throw new ArgumentException("the Type does not derive from ... ");
        }

        base.InsertItem(index, item);
    }
}

Yes. 是。 You have to implement a List that throws exceptions if type is not a subclass from IBase. 如果type不是IBase的子类,则必须实现一个抛出异常的List。

There is no built in way to do what you want. 没有内置的方法可以做你想要的。

The only way to do that is to create your own type collection 唯一的方法是创建自己的类型集合

public class MyTypeList
{
    List<Type> _innerList;

    public void Add(Type type)
    {
        if (typeof(IBase).IsAssignableFrom(type)) {
             _innerList.Add(type);
        } else {
            throw new ArgumentException(
                "Type must be IBase, implement or derive from it.");
        }
    }

    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM