是否有可能拥有泛型List<System.Type>
并对类型有约束?我想将类型存储在列表中以进行查找,但仅限于此类类实现特定接口的类型.
像这样的东西:
List<Type> : where typeof(Type) is IMyClass
Run Code Online (Sandbox Code Playgroud)
那可能吗?如果没有,你对如何解决这个问题有任何建议吗?
任何帮助赞赏!
编辑:
对不起,我对这个问题一直不太清楚,但下面的Sign的评论是正确的,我没有可用的实例,只是类型.
假设如下:
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
Run Code Online (Sandbox Code Playgroud)
是的,我可以包装它,但希望有一个更好的变体,它在编译期间检查或提示intellisense允许哪些类型.
如果我理解正确,你需要一个System.Type列表,它检查它的元素是否实现了某个接口.这很容易实现.只需IList<Type>
通过包装大多数List<Type>
功能并添加几个核对来实现.
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);
}
Run Code Online (Sandbox Code Playgroud)
...
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于基类和接口.
用法示例:
TypeFilteredList list = new TypeFilteredList(typeof(IInterface));
list.Add(typeof(Implementation));
list.Add(typeof(int)); // ArgumentException
Run Code Online (Sandbox Code Playgroud)
但是,如果您不需要IList
功能,则可以实现IEnumerable<Type>
或ISet<Type>
(包装HashSet<T>
).List留下一个选项,可以多次添加相同的类型,在我看来,这是你不想要的东西.
那么你可以编写自己的包装器:
public class ConstrainedList<T> where T : IMyClass
{
private List<T> list;
// Access the list however you want
}
Run Code Online (Sandbox Code Playgroud)
但是,您无法为List<T>
自身添加约束.
您可能希望直接公开包装列表,或者您可能希望实现IList<T>
并将每个成员委派给列表.如果不了解更多关于你想要实现的目标,很难说.