gpt4 book ai didi

c# - 如何在 C# 中将代码块(不是完整方法)作为参数传递?

转载 作者:太空狗 更新时间:2023-10-29 22:32:40 25 4
gpt4 key购买 nike

我正在用 csharp (.net 4.0) 构建一个消息传递应用程序,我的类有发送/接收消息的基本方法:

void sendMessage( string msgBody, string properties);
object getNextMessage();
object getMessageById( string msgId);

这些方法中的每一个都依赖于一个底层连接;如果连接失效,我会使用 try/catch 和一些重试逻辑来进行额外的尝试,如下所示:

public object getNextMessage(){
object nextMessage = null;
int retryAttempts = 0;
int MAX_ATTEMPTS = 3;

while( retryAttempts < MAX_ATTEMPTS){
retryAttempts++;
try{
nextMessage = connection.getMessage("queueName");
}catch(Exception e){
}
}
return nextMessage;
}

由于重试逻辑是通用的,我想避免在每个方法中重复相同的代码。我想创建一个通用的重试函数并执行如下操作:

public object makeAttempt( CodeBlock codeBlock){
while( retryAttempts < MAX_ATTEMPTS){
retryAttempts++;
try{
return codeBlock.invoke()
}catch(Exception e){
}
}
return null;
}

..我想像这样使用makeAttempt,或者类似的东西:

public object getNextMessage(){       
makeAttempt() => {
return connection.getMessage("queueName");
}
}

我评论了this ,但它涉及将整个函数作为参数传递,我没有这样做。我还评论了.net Lambda Expressions ,但我没有看到连接。

我没有做过太多 C#,所以请原谅 n00b 问题:-)

最佳答案

你快到最后了——你只需要将 lambda 表达式括在 () 中,因为它是一个方法参数。您还需要使用 makeAttempt 的返回值来为您的 getNextMessage 方法提供返回值。所以:

public object getNextMessage(){       
return makeAttempt(() => {
return connection.getMessage("queueName");
});
}

或者更简单地说,使用表达式 lambda:

public object getNextMessage(){       
return makeAttempt(() => connection.getMessage("queueName"));
}

这一切都是假设 CodeBlock 是委托(delegate)类型,当然,例如

public delegate object CodeBlock();

您还需要更改 makeAttempt 以调用 Invoke 而不是 invoke - C# 区分大小写。我强烈建议您也遵循 .NET 命名约定,其中方法是 PascalCased 而不是 camelCased

编辑:如评论中所述,您可以将其设为通用:

public T CallWithRetries<T>(Func<T> function)
{
for (int attempt = 1; attempt <= MaxAttempts; attempt++)
{
try
{
return function();
}
catch(Exception e)
{
// TODO: Logging
}
}
// TODO: Consider throwing AggregateException here
return default(T);
}

关于c# - 如何在 C# 中将代码块(不是完整方法)作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19432859/

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