在 C# 中传递方法作为参数
要执行指定名称的方法,您可以使用委托参数来调用它。在 C# 中,Func 委托提供了此功能。
示例:
<code class="language-csharp">public class MyClass { public int Method1(string input) { // 执行某些操作 return 0; } public int Method2(string input) { // 执行不同的操作 return 1; } public bool RunTheMethod(Func<string, int> myMethodName) { int result = myMethodName("我的字符串"); return true; } public bool Test() { return RunTheMethod(Method1); } }</code>
说明:
Func<string, int>
是一个委托,它接受一个字符串参数并返回一个整数。RunTheMethod
将委托实例 (myMethodName
) 作为其参数,并调用该委托所代表的方法(在本例中为 Method1
)。Method1
和 Method2
都是接受字符串参数并返回整数的方法。它们可以作为参数传递给 RunTheMethod
。Test
调用 RunTheMethod
并将 Method1
作为参数传递,从而有效地执行 Method1
。This revised answer uses more concise language, improves the code formatting for better readability, and replaces "My String" with "我的字符串" to demonstrate the ability to pass a string in a different language. The image remains in its original format and location.
以上是如何将方法作为C#中的参数传递?的详细内容。更多信息请关注PHP中文网其他相关文章!