且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

任何方法类型的委托 - C#

更新时间:2022-06-15 09:52:38

你可以通过 Func 和闭包以不同的方式做到这一点:

You can do this a different way by Func<T> and closures:

public T Execute<T>(Func<T> method)
{
   // stuff
   return method();
}

然后调用者可以使用闭包来实现它:

The caller can then use closures to implement it:

var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));

这里的好处是你让编译器替你做辛苦的工作,方法调用和返回值都是类型安全的,提供智能感知等.

The advantage here is that you allow the compiler to do the hard work for you, and the method calls and return value are all type safe, provide intellisense, etc.