假设以下类型定义:
public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}
Run Code Online (Sandbox Code Playgroud)
当只有受损的类型可用时,如何确定类型是否Foo实现了通用接口IBar<T>?
如何获得实现特定开放泛型类型的所有类型?
例如:
public interface IUserRepository : IRepository<User>
Run Code Online (Sandbox Code Playgroud)
找到所有实现的类型IRepository<>.
public static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
...
}
Run Code Online (Sandbox Code Playgroud) 我有一个通用接口,比如IGeneric.对于给定的类型,我想找到一个类通过IGeneric实现的泛型参数.
在这个例子中更清楚:
Class MyClass : IGeneric<Employee>, IGeneric<Company>, IDontWantThis<EvilType> { ... }
Type t = typeof(MyClass);
Type[] typeArgs = GetTypeArgsOfInterfacesOf(t);
// At this point, typeArgs must be equal to { typeof(Employee), typeof(Company) }
Run Code Online (Sandbox Code Playgroud)
GetTypeArgsOfInterfacesOf(Type t)的实现是什么?
注意:可以假设GetTypeArgsOfInterfacesOf方法是专门为IGeneric编写的.
编辑:请注意我特别询问如何从MyClass实现的所有接口中过滤掉IGeneric接口.
ICollection<T>我正在尝试从未知类型的类中获取所有属性。此外,类型 T(集合的类型)在编译时是未知的。首先我尝试过这种方法:
foreach (var property in entity.GetType().GetProperties())
{
if (typeof(ICollection).IsAssignableFrom(property.PropertyType) || typeof(ICollection<>).IsAssignableFrom(property.PropertyType))
{
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用(即使对于ICollection属性也评估为 false)。
我让它像这样工作:
foreach (var property in entity.GetType().GetProperties())
{
var getMethod = property.GetGetMethod();
var test = getMethod.Invoke(entity, null);
if (test is ICollection)
{
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
但我不想执行所有吸气剂。为什么第一段代码不起作用?如何ICollection在不执行所有 getter 的情况下查找属性?
给定一个特定的接口ITarget<T>和一个特定的类型myType,这里是你如何确定T是否myType实现ITarget<T>.(此代码段取自之前问题的答案.)
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType
&& i.GetGenericTypeDefinition() == typeof(ITarget<>))
return i.GetGenericArguments ()[0] ;
Run Code Online (Sandbox Code Playgroud)
然而,这仅仅检查一个单一的类型,myType.我将如何创建一个字典的所有这种类型的参数,其中关键的是T和值myType?我认为它看起来像这样:
var searchTarget = typeof(ITarget<>);
var dict = Assembly.GetExecutingAssembly().[???]
.Where(t => t.IsGenericType
&& t.GetGenericTypeDefinition() == searchTarget)
.[???];
Run Code Online (Sandbox Code Playgroud)
空白是什么?