C# .NET-将方法用作另一个方法的参数
我想使用任何方法作为关心异常处理的方法的参数,如下所示:C# .NET-将方法用作另一个方法的参数,c#,.net,exception,methods,delegates,C#,.net,Exception,Methods,Delegates,我想使用任何方法作为关心异常处理的方法的参数,如下所示: public void Run(){ string result1 = (string)HandlingMethod(GiveMeString, "Hello"); int result2 = (int)HandlingMethod(CountSomething, 1, 2); } public object HandlingMethod(something method, manyDifferentTypesOfPar
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;
}
}
公共类程序
{
公共静态void Main(字符串[]args)
{
stringresult1=(string)测试(newfunc(TestPrint),“hello”);
int result2=(int)测试(新的Func(TestPrint2),4,5);
控制台写入线(结果1);
控制台写入线(结果2);
}
公共静态对象测试(委托方法,参数对象[]args){
控制台写入线(“测试”);
返回方法DynamicInvoke(args);
}
公共静态字符串TestPrint(字符串文本){
返回文本;
}
公共静态int TestPrint2(int n1,int n2){
返回n1+n2+1;
}
}
您可以用C#传递代理
有两种类型:
- 行动:
- 功能:
我在这里看到的唯一问题是,在编写方法时,需要指定委托的参数。当然,您可以将object[]作为参数传递,但我认为这不是一个好主意您可以为每一个参数创建通用处理方法:
public RetType HandlingMethod<P1Type,RetType>(Func<P1Type, RetType> method, P1Type p)
{
return method(p);
}
public RetType HandlingMethod<P1Type, P2Type, RetType>(Func<P1Type, P2Type, RetType> method, P1Type p1, P2Type p2)
{
return method(p1, p2);
}
public RetType处理方法(Func方法,p1p类型)
{
返回法(p);
}
公共RetType处理方法(Func方法、p1类型p1、p2类型p2)
{
返回方法(p1、p2);
}
这将使我的方法加倍。我想为所有事情创建一个方法。我用一个解决方案编辑了这个问题,你怎么看?A1。好的,加倍处理程序,但它们可以用于具有一个或两个参数的其他每一个目标方法。有了object type,你就失去了类型安全性(正如Thomas所说)你为什么不建议我使用object[]?我用一个解决方案编辑了这个问题,你怎么看?@BananaCake如果你使用object[]作为参数,你基本上失去了静态类型语言的所有好处。您必须检查是否收到足够的参数,参数是否不为null,参数是否为正确的类型,并且必须将它们转换为相应的类型。如果您传递了错误的类型,您可能会收到随机异常。我认为您无法执行此类泛型操作。“我不确定它是否安全正常”--您发现的示例是最有效的,因为它创建了一个委托,该委托将使用您提供的参数直接调用您的方法。但是,这并不像要求调用方用匿名方法(通常表示为lambda表达式)包装调用那样方便。后者避免了显式创建委托的需要(例如,通过强制转换或使用new
),这使代码更加可读/简洁。