[英]Get type that implements generic interface by searching for a specific generic interface parameter
我想創建一個方法,該方法返回一個類型(或 IEnumerable 類型),該類型實現一個采用類型參數的特定接口——但是我想通過該泛型類型參數本身進行搜索。 作為示例,這更容易演示:
我想要的方法簽名:
public IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam, Type specificTypeParameter)
然后如果我有以下對象
public interface IRepository<T> { };
public class FooRepo : IRepository<Foo> { };
public class DifferentFooRepo : IRepository<Foo> {};
然后我希望能夠做到:
var repos = GetByInterfaceAndGeneric(typeof(IRepository<>), typeof(Foo));
並獲得一個包含FooRepo
和DifferentFooRepo
類型的 IEnumerable 。
這與此問題非常相似,但是使用該示例,我想通過IRepository<>
和User
進行搜索。
為了重構@lucky 的答案,我更喜歡將類型與泛型類型定義進行比較,而不是使用類型名稱:
static readonly Type GenericIEnumerableType = typeof(IEnumerable<>);
//Find all types that implement IEnumerable<T>
static IEnumerable<T> FindAllEnumerableTypes<T>(Assembly assembly) =>
assembly
.GetTypes()
.Where(type =>
type
.GetInterfaces()
.Any(interf =>
interf.IsGenericType
&& interf.GetGenericTypeDefinition() == GenericIEnumerableType
&& interf.GenericTypeArguments.Single() == typeof(T)));
或者,您可以檢查interf
是否可從GenericIEnumerableType.MakeGenericType(typeof(T))
或其他方式分配。
你可以這樣試試;
public static IEnumerable<Type> GetByInterfaceAndGeneric(Type interfaceWithParam, Type specificTypeParameter)
{
var query =
from x in specificTypeParameter.Assembly.GetTypes()
where
x.GetInterfaces().Any(k => k.Name == interfaceWithParam.Name &&
k.Namespace == interfaceWithParam.Namespace &&
k.GenericTypeArguments.Contains(specificTypeParameter))
select x;
return query;
}
用法;
var types = GetByInterfaceAndGeneric(typeof(IRepository<>), typeof(Foo)).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.