c# - .NET - 使用方法作为另一个方法的参数
问题描述
我想使用任何方法作为关心异常处理的方法的参数,如下所示:
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;
}
}
解决方案
您可以在 C# 中传递委托。
有两种类型:
- 行动:https ://docs.microsoft.com/de-de/dotnet/api/system.action-1?view=netframework-4.8
- 功能:https ://docs.microsoft.com/de-de/dotnet/api/system.func-2?view=netframework-4.8
Action 没有返回值,Function 有返回值。我在这里看到的唯一问题是,您需要在编写方法时指定委托的参数。当然你可以将 object[] 作为参数传递,但我认为这不是一个好主意
推荐阅读
- keras - 我想为分类定制 VGG 19 架构的最后一层。keras 和 pytorch 哪个更有用?
- sql - 在 Access 中同步 SQL Server 元数据?
- python - 我正在使用python 2.7。我尝试了所有方法来设置 xlrd 文件,但我仍然收到错误:ImportError: No module named xlrd >>>
- c++ - 为什么返回具有引用类型的局部变量在 VS2012 中有效
- r - 在 R 中按时间和组获取第一个唯一值
- regex - 基于 URL 和查询字符串的 Htaccess 重定向
- javascript - 重构 firebase 函数 index.ts 代码,以便可以导入触发器
- c# - 实体框架正在参数化我的查询以利用缓存
- html - 如何使用带有条件类的类
- jquery - Phonegap Build 6.5,iOS ... ajax 调用不起作用