gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:59:54 25 4
gpt4 key购买 nike

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

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:有没有办法将委托(delegate)发送给

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

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

public BillingStatusResult CheckBillingStatus(BillingOperationRequestDto dto)
{
}
public AnotherReturnValue AnotherOperationOnBilling(BillingOperationRequestDto dto, string requestedIp, TimeSpan period)
{
}

最佳答案

正如@juharr 已经提到的,您可以使用通用委托(delegate)(如果您需要从委托(delegate)检索结果,它的类型为 Action<T>Func<T, TResult>)。

您可以在 this 中找到更多信息问题或documentation

class MessageListener<T> where T : BaseDto {
public void GetMessage<T>(Action<T> action)
{
}

MessageListener<T>(string queueToListen)
{
}
}

关于c# - 如何通过Func发送一个方法执行到C#中的另一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51845750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com