【发布时间】:2019-09-26 11:32:44
【问题描述】:
我想使用任何方法作为关心异常处理的方法的参数,如下所示:
public void Run(){
string result1 = (string)HandlingMethod(GiveMeString, "Hello");
int result2 = (int)HandlingMethod(CountSomething, 1, 2);
}
public object HandlingMethod(something method, manyDifferentTypesOfParameters...){
try{
return method(manyDifferentTypesOfParameters)
}catch(Exception ex){
....
}
}
public string GiveMeString(string text){
return text + "World";
}
public int CountSomething(int n1, int n2){
return n1 + n2;
}
是否可以在 C# .Net 中做到这一点?
编辑:
我找到了这个解决方案,但我不确定它是否安全和正常。你怎么看?
public class Program
{
public static void Main(string[] args)
{
string result1 = (string)Test(new Func<string,string>(TestPrint), "hello");
int result2 = (int)Test(new Func<int, int, int>(TestPrint2), 4, 5);
Console.WriteLine(result1);
Console.WriteLine(result2);
}
public static object Test(Delegate method, params object[] args){
Console.WriteLine("test test");
return method.DynamicInvoke(args);
}
public static string TestPrint(string text){
return text;
}
public static int TestPrint2(int n1, int n2){
return n1 + n2 +1;
}
}
【问题讨论】:
-
我不认为你可以做这种通用的事情。
-
“我不确定它有多安全和好” - 您找到的示例是最有效的,因为它创建了一个直接调用您的方法的委托,以及您提供的论点。但是,它不如要求调用者将其调用包装在匿名方法(通常表示为 lambda 表达式)中那么方便。后者避免了显式创建委托的需要(例如通过强制转换或使用
new),这使代码更具可读性/简洁性。
标签: c# .net exception methods delegates