c# - 如何在泛型服务中调用泛型方法?
问题描述
我有一个通用类,其中一个字段是通用服务。在这个类中,我有一个名为 InitialQueue 的方法,其目的是调用我将其提供给 InitialQueue 方法的通用服务方法之一。我的问题是我不知道如何调用该方法。
public class RabbitConsumer<I, E> : IHostedService
where I : class
where E : class
{
private readonly I service;
public RabbitConsumer(I service)
{
this.service = service;
}
public RabbitConsumer(Expression<Func<I, Func<E, object>>> method, IConfiguration config, string entryQueueName) : base()
{
InitialQue(method);
}
public Task StartAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Dispose();
return Task.CompletedTask;
}
private void InitialQue(Expression<Func<I, Func<E, object>>> method)
{
//For example this is the object that I get through RabbitMq
var myObject = JsonConvert.DeserializeObject<E>(new { Id = 1, Name = "My Category"});
//I need something like that but I don't have any idea what to do
service.Invoke(method(myObject));
}
}
解决方案
正如 Mong Zhu 所提到的,如果您有资格获得更多传入的仿制药,例如
where I : class
您还可以添加其他内容,例如 new() 如果对象类型允许“new”创建新实例,或者其他可以公开您尝试访问的方法的接口。简单的改变就像
where I : class, new(), ICanDoThisInterface, ICanDoThatInterface
所以现在,无论你有“I”泛型,比如存储在“服务”字段中,你都可以这样做
var tmp = new I();
tmp.MethodFromTheICanDoThisInterface();
tmp.MethodFromTheICanToThatInterface();
推荐阅读
- django - 如何使用本地 yml 模式文件将 Redoc 文档添加到 Django?
- .net-core - .NET CORE - 当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头不能是通配符“*”
- css - @media (prefers-color-scheme: light) 在 chrome 中不起作用
- java - 如何为自定义 api 错误消息解决此错误。如果我删除了此类的两个方法,则项目运行没有错误
- jquery - 将模型传递给 jQuery
- reactjs - “是的”验证库无法在 TypeScript 中编译
- google-cloud-platform - AttributeError:“StreamExhausted”对象没有属性“消息”。流中的字节数不足;预计1265662718,
- java - 程序直接进入else语句
- node.js - 如何使用 express-oauth-server 进行身份验证?
- r - 如何跨多个列匹配列并在新列中返回匹配的 col_name