Home >Backend Development >C++ >How Can I Pass a Method as a Parameter in C#?

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

Susan Sarandon
Susan SarandonOriginal
2025-02-01 01:26:13391browse

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

Passing in C# as a parameter

To execute the specified name method, you can use the commission parameter to call it. In C#, Func commissioned this feature.

Example:

Explanation:

<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>

is a commission that accepts a string parameter and returns an integer.

The entrusted instance (
    ) is used as its parameter and the method represented by the commission (
  • in this example). Func<string, int>
  • and
  • both are methods to accept string parameters and return an integer. They can be passed to RunTheMethod as a parameter. myMethodName Method1 Call
  • and transmit it as a parameter to effectively execute
  • . Method1 Method2 RunTheMethod This Revised Answer's More Concise Language, Improves The Code Formatting for Better Readability, and Replaces "My String" With "to Demonstrate The Abilital to Pass A String in a Different Language. Original format and local.

The above is the detailed content of How Can I Pass a Method as a Parameter in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn