【发布时间】:2023-03-28 08:36:01
【问题描述】:
如何在程序集中找到作为通用抽象类的实例并实现某个接口的所有类?
注意:
该接口也可以在从另一个实现该接口的类继承的类中实现。
一个具体的例子:
我有波纹管接口和中间件类:
public interface IHttpHandler
{
bool IsReusable { get; }
void ProcessRequest(HttpContext context);
}
public abstract class HandlerMiddleware<T> where T: IHttpHandler
{
private readonly RequestDelegate _next;
public HandlerMiddleware()
{ }
public HandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
await SyncInvoke(context);
}
public Task SyncInvoke(HttpContext context)
{
// IHttpHandler handler = (IHttpHandler)this;
T handler = System.Activator.CreateInstance<T>();
handler.ProcessRequest(context);
return Task.CompletedTask;
}
} // End Abstract Class HandlerMiddleware
我怎样才能找到像 HelloWorldHandler 这样实现抽象类并实现 IHttpHandler 的所有类。
请注意,HandlerMiddleware 是通用的。
它应该找到所有处理程序,例如HelloWorldHandler1 和 HelloWorldHandler2。
[HandlerPath("/hello")]
public class HelloWorldHandler
: HandlerMiddleware<HelloWorldHandler>, IHttpHandler
{
public HelloWorldHandler() :base() { }
public HelloWorldHandler(RequestDelegate next):base(next) { }
void IHttpHandler.ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//await context.Response.WriteAsync("Hello World!");
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("hello world");
context.Response.Body.Write(buffer, 0, buffer.Length);
}
bool IHttpHandler.IsReusable
{
get
{
return false;
}
}
}
如果该方法也找到此构造,则加分:
[HandlerPath("/hello2")]
public class HelloWorldHandler2
: HandlerMiddleware<Middleman>
{
public HelloWorldHandler2() :base() { }
public HelloWorldHandler2(RequestDelegate next):base(next) { }
}
public class Middleman
: IHttpHandler
{
bool IHttpHandler.IsReusable => throw new NotImplementedException();
void IHttpHandler.ProcessRequest(HttpContext context)
{
throw new NotImplementedException();
}
}
【问题讨论】:
-
结构 HandlerMiddleware
的所有类,其中 已实现 IHttpHandler(无论实现本身是否抛出未实现)。 -
这个“发现”的上下文是什么?您是在寻找有关如何使用 Visual Studio 的建议,还是想编写在运行时执行此搜索的反射代码?
-
@Damien_The_Unbeliever:问得好。我的意思是在运行时搜索。
-
只需使用
typeof(HandlerMiddleware).IsAssignableFrom(type) && typeof(IHttpHandler).IsAssignableFrom(type)。展开成typeof(type-in-assembly).Assembly.GetTypes().Where(t => typeof(HandlerMiddleware).IsAssignableFrom(t)&& typeof(IHttpHandler).IsAssignableFrom(type)).ToArray();
标签: c# asp.net .net asp.net-core .net-core