在 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中文網其他相關文章!