Is List that accepts only certain types po

2020-07-23 08:36发布

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.

Something like this:

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

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

Any help appreciated !

EDIT:

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

Assume the following:

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.

标签: c#
7条回答
贼婆χ
2楼-- · 2020-07-23 09:23

You can try using generics like this:

 class EmployeeList<T> where T : IMyClass
 {
     // ...
 }
查看更多
登录 后发表回答