为list<&的System.Type GT;仅接受某些类型的可能? [英] Is List<System.Type> that accepts only certain types possible?

查看:105
本文介绍了为list<&的System.Type GT;仅接受某些类型的可能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有一个通用的列表与LT; System.Type的> 和对类型约束?
我想存储类型在查找列表,但只有类型那里的此种类型的类实现一个特定的接口

is there any possibility to have a generic List<System.Type> and to have a constraint on the type? I want to store types in a list for a lookup, but only types where the class of this type implements a specific interface.

事情是这样的:

List<Type> : where typeof(Type) is IMyClass



这可能吗?如果不是你有关于如何解决此问题的任何建议?

Is that possible? If not do you have any suggestion on how to solve this issue?

任何帮助感激!

编辑:

对不起,我没有得到关于这个问题的更清晰,但低于注册的评论是正确的,我没有实例可用,只是类型

Sorry I haven't been clearer on the subject, but Sign's comment below is correct, I don't have instances available, just types.

假设如下:

class PluginA : IPlugin { } 
class PluginB : IPlugin { } 
class PluginC : ISomeOtherInterface { } 

var pluginTypes = new List<Type>()
pluginTypes.Add(typeof(PluginA) --> OK
pluginTypes.Add(typeof(PluginB) --> OK
pluginTypes.Add(typeof(PluginC) --> should fail

是的,我可以换这一点,但希望会有一个更好的变体,它编译时或暗示具有智能感知类型允许哪些过程中检查。

Yes I could wrap this, but hoped that there would be a better variant which checks during compiletime or hints with intellisense what types are allowed.

推荐答案

如果我理解正确的,你想要的System.Type的一个列表,它会检查它的元素实现某个接口。这是很容易做到。刚刚实施的IList<类型> 通过包装大部分列表<类型方式> 功能,并添加一些体检的

if I understood you correctly, you want a list of System.Type which checks that its elements implement a certain interface. This is easy to accomplish. Just implement IList<Type> by wrapping most the List<Type> functionality and add a couple of checkups.

public class TypeFilteredList : IList<Type>
{
    private Type filterType;
    private List<Type> types = new List<Type>();

    public TypeFilteredList(Type filterType)
    {
        this.filterType = filterType;
    }

    private void CheckType(Type item)
    {
        if (item != null && !filterType.IsAssignableFrom(item))
            throw new ArgumentException("item");
    }

    public void Add(Type item)
    {
        CheckType(item);
        types.Add(item);
    }

    public void Insert(int index, Type item)
    {
        CheckType(item);
        types.Insert(index, item);
    }



...

...

}

这段代码将为基类以及工作。因为接口

this code will work for base classes as well as interfaces.

实例:

TypeFilteredList list = new TypeFilteredList(typeof(IInterface));
list.Add(typeof(Implementation));
list.Add(typeof(int)); // ArgumentException



不过,若你不需要的IList 的功能,可以实现的IEnumerable<类型> 的ISet<类型> (包装 HashSet的< T> )。叶列出的选项添加同一类型的好几倍,这在我看来是的东西,你不想要的。

If you however don't need IList functionality, you can implement IEnumerable<Type> or ISet<Type> (wrapping HashSet<T>). List leaves an option to add the same type several times, which it seems to me is something, you don't want.

这篇关于为list&LT;&的System.Type GT;仅接受某些类型的可能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆