C# 委托可以指向另一个 class/object 的方法吗?

Could C# delegate point to another class/object's method?

在这里,我希望获得一个类似于函数指针的委托,指向另一个 class(名为 Inner)中的 class 方法,然后将其传递给静态函数,例如下面:

public class Inner
{
    public int M = 3;
    public void F() { Console.WriteLine("f"); }
    public void G() { Console.WriteLine("g"); }
}
class Program
{
    public static void Caller(Action a)
    {
        a();
    }
    static void Main(string[] args)
    {
        var i = new Inner();
        var f = i.F;
        var g = i.G;
        f();//error
        g();//error
        Program.Caller(f);
        Console.WriteLine("Hello World!");
    }
}

我来自c/c++,在c/c++中,像这样的函数指针非常直接,但是这段C#代码无法编译。我用谷歌搜索,发现几乎所有委托解释都谈到委托本身指向 class 方法。

我的问题是,如何修复代码以使其正常工作?

您不能在 C# 中的隐式变量中设置方法组,因此如果您只更改 Action 中的 2 var 它就可以工作

public class Inner
{
    public int M = 3;
    public void F() { Console.WriteLine("f"); }
    public void G() { Console.WriteLine("g"); }
}
class Program
{
    public static void Caller(Action a)
    {
        a();
    }
    static void Main(string[] args)
    {
        var i = new Inner();
        Action f = i.F;
        Action g = i.G;
        f();
        g();
        Program.Caller(f);
        Console.WriteLine("Hello World!");
    }
}

突出显示了问题的原因,但并未真正解释原因。

因为i.F是一个方法组,而不是具体的方法指针。例如,假设 Inner 定义为:

public class Inner
{
    public void F() { Console.WriteLine("f"); }
    public void F(string name) { Console.WriteLine(name); }
}

i.F指的是哪个方法? F()F(string)?

因此,您需要显式定义变量类型,或转换指针:

Action f = i.F;

或:

var f = (Action)i.F;