使用C#传递方法参数 [英] Pass Method as Parameter using C#

查看:291
本文介绍了使用C#传递方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几种方法都具有相同签名(参数和返回值),但不同的名称和这些方法的内部不同。我想通过方法的名称来运行,这将在调用方法传递的另一种方法。

I have several methods all with the same signature (parameters and return values) but different names and the internals of the methods are different. I want to pass the name of the method to run to another method that will invoke the passed in method.

public int Method1(string)
{
    ... do something
    return myInt;
}

public int Method2(string)
{
    ... do something different
    return myInt;
}

public bool RunTheMethod([Method Name passed in here] myMethodName)
{
    ... do stuff
    int i = myMethodName("My String");
    ... do more stuff
    return true;
}

public bool Test()
{
    return RunTheMethod(Method1);
}

这code不工作,但是这是我想要做的事。我不明白是怎么写的RunTheMethod code,因为我需要定义的参数。

This code does not work but this is what I am trying to do. What I don't understand is how to write the RunTheMethod code since I need to define the parameter.

推荐答案

您可以使用.NET 3.5中的函数功能委托作为你的RunTheMethod方法的参数。该函数功能委托允许你指定需要一些特定类型的参数,并返回一个特定类型的单个参数的方法。下面是应该工作的例子:

You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

这篇关于使用C#传递方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆