【问题标题】:C# Pass type (class) method like parameterC#传递类型(类)方法,如参数
【发布时间】:2021-08-03 05:40:43
【问题描述】:

我想将一个方法从类型(类)像参数一样传递给另一个方法,我不知道该怎么做。

    class Program
    {
        static void Main(string[] args)
        {
            MyMethod(Foo.MethodA);
            MyMethod(Foo.MethodB);
        }

        public void MyMethod(???)
        {
        }
    }

    public class Foo
    {
        public void MethodA()
        {
        }

        public int MethodB(int val)
        {
            return val;
        }
    }

我只想这样做

    MyMethod(Foo.MethodA);

我不想从对象传递方法,而只是从类型(类)传递方法

【问题讨论】:

  • 使用Func 类型
  • 查找Delegate。 @RufusL 谈到的 Func 类型(以及类似的 Action 类型)是代表。
  • 请注意,在您的情况下,您的 Foo.MethodA() 是一个没有参数的 void 函数,而 Foo.MethodB() 将一个 int 作为参数并返回一个 int。它们不是同一类型(好吧,除了它们都可以表示为delegate)。 MethodA 可以用Action 表示,而MethodB 可以用Func<int, int> 表示。你需要非常努力地在MyMethod 中实现任何有用的东西,因为传入的参数是如此不同
  • @JulioGold 你真的需要告诉我们你想用传递的方法做什么,这样我们才能弄清楚如何做你想做的事情。

标签: c# class types parameters


【解决方案1】:

我不确定您要做什么,但您可以将方法概括为Delegate

static void Main(string[] args)
{
    MyMethod(new Action(Foo.MethodA));
    MyMethod(new Func<int,int>(Foo.MethodB));
}

public static void MyMethod(Delegate del)
{
    // Example code
    var methodInfo = del.Method;
    var methodName = methodInfo.Name;
}

您仍然需要将方法包装在一些委托中,例如 ActionFunc&lt;&gt;

【讨论】:

    猜你喜欢
    • 2011-07-27
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多