【问题标题】:.NET - Use method as a parameter of another method [duplicate].NET - 使用方法作为另一个方法的参数[重复]
【发布时间】: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


【解决方案1】:

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

有两种类型:

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

【讨论】:

  • 为什么不推荐我使用object[]?
  • 我用一个解决方案编辑了这个问题,你怎么看?
  • @BananaCake 如果你使用 object[] 作为参数,你基本上失去了静态类型语言的所有好处。您必须检查,如果您收到足够的参数,参数是否不为空,参数是否是正确的类型,您必须将它们转换为相应的类型。如果你传递了错误的类型,你可能会收到随机异常
【解决方案2】:

您可以为每个参数数量创建通用处理方法:

    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);
    }

【讨论】:

  • 这只会使我的方法加倍。我想为所有事情创建一种方法。
  • 我用一个解决方案编辑了这个问题,你怎么看?
  • A1.好的,双倍的处理程序,但它们可以用于具有一个或两个参数 A2 的所有其他目标方法。使用对象类型,您会失去类型安全性(正如 Thomas 所说)
猜你喜欢
  • 2013-07-01
  • 2011-07-21
  • 1970-01-01
  • 2015-12-16
  • 2016-12-03
  • 2012-11-06
  • 2018-08-08
相关资源
最近更新 更多