如何通过Func将要执行的方法发送到C#中的另一个方法?

我有一个如下所示的服务类:


class BillingService

{

    public void CheckBillingStatus(BillingOperationRequestDto dto)

    {

    }


    public void AnotherOperationOnBillings(BillingOperationRequestDto dto)

    {

    }

}

此外,我还有另一个班级,可以从 RabbitMq 收听一些队列。我想写一些类似的东西:


class MessageListener<T> where T : BaseDto {

        public void GetMessage<T>(Func ... )


        MessageListener<T>(string queueToListen)

        {

        }

}

这段代码背后的想法是我想将它用作:


BillingService bs = new BillingService();

var listener = new MessageListener<BillingOperationRequestDto>();


listener.GetMessage<BillingOperationRequestDto>(bs.CheckBillingStatus);

我不仅要指定队列中预期的数据,还要指定对该数据调用的方法。这是正确的方法吗?我想只从队列中获取一条消息,而不是将数据发送到另一个类,但没有找到一个方法来执行此操作,因此决定循环运行 GetMessage 并指定出现消息时应执行的操作。


更新 #1.1:有没有办法将委托发送到


listener.GetMessage<BillingOperationRequestDto>(bs.CheckBillingStatus);

如果我在 BillingService 类中的方法会有不同的方法签名?例如,


public BillingStatusResult CheckBillingStatus(BillingOperationRequestDto dto)

{

}

public AnotherReturnValue AnotherOperationOnBilling(BillingOperationRequestDto dto, string requestedIp, TimeSpan period)

{

}


临摹微笑
浏览 306回答 2
2回答

慕村225694

你可以使用泛型委托(有类型Action<T>或者Func<T, TResult>如果你需要从委托检索结果)。您可以在此问题或文档中找到更多信息class MessageListener<T> where T : BaseDto {&nbsp; &nbsp; public void GetMessage<T>(Action<T> action)&nbsp; &nbsp; {&nbsp; &nbsp; }&nbsp; &nbsp; MessageListener<T>(string queueToListen)&nbsp; &nbsp; {&nbsp; &nbsp; }}

慕无忌1623718

AFunc<T, TResult>是返回结果的委托。您会想要使用Action<T>,它不会返回结果。您的泛型类型参数Action<T>必须与您将传递的方法的签名相匹配。通常,当使用来自消息队列的消息时,您将有一个侦听器类为该消息队列包装客户端,并且您将在侦听器中处理 MessageReceived 事件(我是笼统地说 - 我没有专门与 RabbitMQ 合作)。所以你的听众可能看起来像这样(伪代码):class MessageListener<T> where T : BaseDto {&nbsp; &nbsp; var _client = new QueueClient();&nbsp; &nbsp; MessageListener<T>(string queueToListen, Action<T> onMessageReceived)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; _client = new QueueClient("<your_connection_string>", queueToListen);&nbsp; &nbsp; &nbsp; &nbsp; _client.MessageReceived += onMessageReceived;&nbsp; &nbsp; }}用法将是这样的:BillingService bs = new BillingService();var listener = new MessageListener<BillingOperationRequestDto>("myQueue", bs.CheckBillingStatus);
打开App,查看更多内容
随时随地看视频慕课网APP