反映具有约束的泛型类型的所有可能排列
给定一个带有约束的泛型类型:
class MyClass<T> where T: Alpha
{
}
以及该约束的实现:
class Alpha {}
class Bravo : Alpha {}
class Charlie : Alpha {}
如何在运行时获取所有组合的泛型类型?
// I want these types at run-time
MyClass<Alpha>
MyClass<Bravo>
MyClass<Charlie>
编辑:根据@rich.okelly的回答,我认为真正的问题是:
如何找到在运行时实现泛型类型约束的所有类型?
因此,如果给我 typeof(MyClass<>)
,我就会得到上面的类型。
Given a generic type with constraints:
class MyClass<T> where T: Alpha
{
}
and implementations of that constraint:
class Alpha {}
class Bravo : Alpha {}
class Charlie : Alpha {}
How can get generic types for all the combinations at run-time?
// I want these types at run-time
MyClass<Alpha>
MyClass<Bravo>
MyClass<Charlie>
EDIT: Based on @rich.okelly's answer, I think the real question is this:
How can I find all the types that implement my generic type's constraint at run-time?
So if I'm given typeof(MyClass<>)
, I get the types above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
例如:
或者,如果通用类型已经加载:
更新
您可以使用
GetGenericArguments()
方法 和GetGenericParameterConstraints()
方法获取所需的类型。Something like:
Alternatively, if the generic types have already been loaded:
Update
You can use the
GetGenericArguments()
method and theGetGenericParameterConstraints()
method to get the required types.您可以枚举应用程序域中所有加载的程序集。然后枚举每个程序集中的所有类型并测试每个类型是否是 常量的子类。
You can enumerate all loaded assemblies in the app domain. And then enumerate all the types in each Assembly and test to see if each type is a subclass of the constant.