【发布时间】:2021-05-27 06:55:15
【问题描述】:
我需要关于如何实施以下内容的建议或想法。我有一个接口,其中包含许多方法,每个方法都可以抛出异常(实际上是 WCF 调用)。所以每个调用必须用 try 块包装
public interface ISomeInterface
{
MethodThatCanThrow1(Arg1 arg);
..
MethodThatCanThrow101(Arg2 arg);
}
现在我们有一个对象集合
var items = new List<ISomeInterface>();
现在我必须为每个对象循环调用 MethodThatCanThrow1 方法。方法可能会抛出异常,在这种情况下我需要继续处理剩余的对象
void CallMethodThatCanThrow1()
{
foreach(var item in items)
{
try
{
item.MethodThatCanThrow1(Arg1 arg);
}
catch(Exception ex)
{
// do something
}
}
}
现在我需要调用 MethodThatCanThrow2 所以对于第二种方法,我需要复制粘贴 try catch 块的内容。
void CallMethodThatCanThrow2()
{
foreach(var item in items)
{
try
{
item.MethodThatCanThrow2(Arg2 arg);
}
catch(Exception ex)
{
// remove failed item from items
// continue foreach for the rest
}
}
}
所以对于其余的 101 方法,我必须复制粘贴整个块,只更改方法名称。
所以我正在考虑重构它。我想要的是将try catch块放在单独的Method中并传递需要调用的Method Name
void CallMethodofISomeInterfaceForGivenReference(delegate methodProvide)
{
foreach(var item in items)
{
try
{
// take item and call method that is provided
}
catch(Exception ex)
{
// do something
}
}
}
【问题讨论】:
-
注意:在foreach循环中不能修改列表。
-
您已经提出了解决方案,那么您的问题是什么?
-
@CaptainComic 您可以使用反射,但这完全没有必要,因为您可以通过委托。例如,您可以拥有
void TryCatchWrapper(Action action)。或者您可以使用表达式,因此您可以使用 lambda,甚至 ... -
^^ 见dotnetfiddle.net/uczmrI 一个简单的例子。
-
@Fildor 是对的:为什么要传递一个不是类型安全的方法名称,而不是一个 类型安全的委托?
标签: c# exception design-patterns foreach delegates