![](/img/trans.png)
[英]What does the class type constraint achieve if a generic type constraint must also implement an interface in c#
[英]C# find all class implement interface without generic type
我有Generic Type
Interface
public interface IWork<T>
{
void Work(MySession session, T json);
}
我试图在尝试此代码时找到所有实现具有所有泛型类型的Interface
Classes
var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
它自己返回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> { }
您可以从结果中添加到Where.p.IsInterface或p.IsClass以远程接口。
var type = typeof(IWork<>);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p) && !p.IsInterface);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.