首页 > 解决方案 > 如何在泛型服务中调用泛型方法?

问题描述

我有一个通用类,其中一个字段是通用服务。在这个类中,我有一个名为 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));
    }
}

标签: c#genericsexpressiongeneric-method

解决方案


正如 Mong Zhu 所提到的,如果您有资格获得更多传入的仿制药,例如

  where I : class

您还可以添加其他内容,例如 new() 如果对象类型允许“new”创建新实例,或者其他可以公开您尝试访问的方法的接口。简单的改变就像

  where I : class, new(), ICanDoThisInterface, ICanDoThatInterface

所以现在,无论你有“I”泛型,比如存储在“服务”字段中,你都可以这样做

var tmp = new I();
tmp.MethodFromTheICanDoThisInterface();
tmp.MethodFromTheICanToThatInterface();

推荐阅读