c#方法参数传递:实用指南
>c#提供了一种将方法作为参数传递到其他方法的强大机制,从而显着增强了代码灵活性和可重复性。这是使用代表实现的。
>下面的示例说明了一个常见问题:尝试将方法名称传递给另一个方法(RunTheMethod
),而无需正确指定参数。 由于参数定义不足。
RunTheMethod
解决方案涉及采用
表示接受类型Func
的参数并返回类型Func<T, TResult>
>的方法。 这允许在接收方法中进行精确的参数规范。T
>
TResult
这是一个校正的代码段,演示了
Func
接受a
<code class="language-csharp">public class Class1 { public int Method1(string input) { // ... perform operations ... return 0; } public int Method2(string input) { // ... perform different operations ... return 1; } public bool RunTheMethod(Func<string, int> myMethodName) { // ... initial operations ... int result = myMethodName("My String"); // ... subsequent operations ... return true; } public bool Test() { return RunTheMethod(Method1); } }</code>>和
匹配此签名,使它们能够成功传递。RunTheMethod
>
Func<string, int>
该技术使用委托有助于动态方法调用,并显着提高代码模块性和可维护性。
以上是如何将方法作为C#中的参数传递?的详细内容。更多信息请关注PHP中文网其他相关文章!