首頁 > 後端開發 > C++ > 如何將方法作為C#中的參數傳遞?

如何將方法作為C#中的參數傳遞?

Susan Sarandon
發布: 2025-02-01 01:26:13
原創
389 人瀏覽過

How Can I Pass a Method as a Parameter in C#?

在 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)。
  • Method1Method2 都是接受字符串參數並返回整數的方法。它們可以作為參數傳遞給 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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板