给定具有约束的泛型类型:
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.
最满意答案
就像是:
var alphaType = typeof(Alpha); var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => alphaType.IsAssignableFrom(t)); var myClass = typeof(MyClass<>); foreach (var type in allTypes) { var genericType = myClass.MakeGenericType(type); }或者,如果已经加载了泛型类型:
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(MyClass<>)); foreach (var type in allTypes) { ... }更新
您可以使用GetGenericArguments()方法和GetGenericParameterConstraints()方法来获取所需的类型。
var myType = typeof(MyClass<>); var typeConstraints = myType.GetGenericArguments().First().GetGenericParameterConstraints(); var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()); var genericTypes = allTypes.Where(t => typeConstraints.All(tc => tc.IsAssignableFrom(t))).Select(t => myType.MakeGenericType(t)); foreach (var type in genericTypes) { ... }Something like:
var alphaType = typeof(Alpha); var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => alphaType.IsAssignableFrom(t)); var myClass = typeof(MyClass<>); foreach (var type in allTypes) { var genericType = myClass.MakeGenericType(type); }Alternatively, if the generic types have already been loaded:
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(MyClass<>)); foreach (var type in allTypes) { ... }Update
You can use the GetGenericArguments() method and the GetGenericParameterConstraints() method to get the required types.
var myType = typeof(MyClass<>); var typeConstraints = myType.GetGenericArguments().First().GetGenericParameterConstraints(); var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()); var genericTypes = allTypes.Where(t => typeConstraints.All(tc => tc.IsAssignableFrom(t))).Select(t => myType.MakeGenericType(t)); foreach (var type in genericTypes) { ... }更多推荐
发布评论