C#委托可以指向另一个类/对象的方法吗?

问题描述 投票:1回答:2

这里,我希望获得一个像函数指针一样的委托,以指向另一个类(名为Inner)中的类方法,然后将其传递给静态函数,如下所示:

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#代码无法编译。我在Google上搜索后发现,几乎所有有关委托的说明都指向其内部指向类方法的委托。

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

c# function class methods delegates
2个回答
2
投票

Coding Seb's answer高亮是问题的原因,但并没有真正解释原因。

这是因为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;

1
投票

您无法在C#中的隐式变量中设置方法组,因此,如果仅在var中更改2 Action,则该方法有效

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!");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.