首页 > 解决方案 > .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#.netexceptionmethodsdelegates

解决方案


您可以在 C# 中传递委托。

有两种类型:

Action 没有返回值,Function 有返回值。我在这里看到的唯一问题是,您需要在编写方法时指定委托的参数。当然你可以将 object[] 作为参数传递,但我认为这不是一个好主意


推荐阅读