[英]How can I use reflection to find which open generic argument on an open generic type implements a generic interface?
[英]How can I use reflection to return all classes subclassing from a generic, without giving a specific generic type
我正在嘗試使用反射編寫一個方法來返回所有類,這些類是使用泛型的類的子類,而不受泛型類型的限制。 例如,在EF中我想找到所有的映射類。 這些類的設置如下:
public class clientMap : EntityTypeConfiguration<Client> {}
我想在我的程序集中找到EntityTypeConfiguration<T>
的子類中的所有類,而不是特別指定Client
作為T。 我想在我的應用程序中為所有類返回實體類型配置,而不對其進行硬編碼。
如果沒有泛型,我會循環遍歷程序type.IsSubclassOf(typeof(BaseClass))
的類型,檢查是否type.IsSubclassOf(typeof(BaseClass))
,但是我不知道在處理泛型時如何做到這一點。
我相信你想要這樣的東西:
static class TypeExtensions {
public static bool IsDerivedFromOpenGenericType(
this Type type,
Type openGenericType
) {
Contract.Requires(type != null);
Contract.Requires(openGenericType != null);
Contract.Requires(openGenericType.IsGenericTypeDefinition);
return type.GetTypeHierarchy()
.Where(t => t.IsGenericType)
.Select(t => t.GetGenericTypeDefinition())
.Any(t => openGenericType.Equals(t));
}
public static IEnumerable<Type> GetTypeHierarchy(this Type type) {
Contract.Requires(type != null);
Type currentType = type;
while (currentType != null) {
yield return currentType;
currentType = currentType.BaseType;
}
}
}
這些測試通過:
class Foo<T> { }
class Bar : Foo<int> { }
class FooBar : Bar { }
[Fact]
public void BarIsDerivedFromOpenGenericFoo() {
Assert.True(typeof(Bar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
[Fact]
public void FooBarIsDerivedFromOpenGenericFoo() {
Assert.True(typeof(FooBar).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
[Fact]
public void StringIsNotDerivedFromOpenGenericFoo() {
Assert.False(typeof(string).IsDerivedFromOpenGenericType(typeof(Foo<>)));
}
據我所知,你的情況應該足夠了
type.BaseType != null &&
type.BaseType.MetadataToken == typeof(EntityTypeConfiguration<>).MetadataToken
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.