Moh*_*Ali 4 c# reflection typeof
我有Interface与Generic Type
public interface IWork<T>
{
void Work(MySession session, T json);
}
Run Code Online (Sandbox Code Playgroud)
尝试此代码时Classes,我试图找到所有实现Interface所有泛型类型的
var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Run Code Online (Sandbox Code Playgroud)
它返回Interface它自己。
问题是没有类/接口会直接扩展泛型接口,它们都会为给定的类型参数(无论是具体类型,string还是其他类型参数)扩展泛型接口的实例化。您需要检查类实现的任何接口是否是通用接口的实例:
class Program
{
static void Main(string[] args)
{
var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => p.GetInterfaces().Any(i=> i.IsGenericType && i.GetGenericTypeDefinition() == type))
.ToArray();
// types will contain GenericClass, Cls2,Cls,DerivedInterface defined below
}
}
public interface IWork<T>
{
void Work(object session, T json);
}
class GenericClass<T> : IWork<T>
{
public void Work(object session, T json)
{
throw new NotImplementedException();
}
}
class Cls2 : IWork<string>
{
public void Work(object session, string json)
{
throw new NotImplementedException();
}
}
class Cls : GenericClass<string> { }
interface DerivedInterface : IWork<string> { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2161 次 |
| 最近记录: |