各地成员函数传递在C#

各地成员函数传递在C#

问题描述:

主要是它来得心应手,C#语言的代表已经与成员函数一起存储对象。但有一个办法,来存储 - 而作为参数传递 - 只有成员函数本身,就像在C良好的老指针到成员函数++

Mostly it comes handy that C# delegates already store the object together with the member function. But is there a way, to store -- and pass as parameters -- only the member function itself, just as the good old pointer-to-member-function in C++?

在的情况下的说明是小于清楚,我给一个自包含的例子。是的,在这个例子中坚持以绕过成员函数是完全没有意义的,但我对这个更严重的用途。

In case the description is less than clear, I give a self-contained example. And, yes, in the example the insistence to pass around member functions is totally pointless, but I have more serious uses for this.

class Foo {
    public int i { get; set; }
    /* Can this be done?
    public static int Apply (Foo obj, ???? method, int j) {
        return obj.method (j);
    }
    */
    public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
        return (int) method.Method.Invoke (obj, new object [] { j });
    }
    public static readonly Foo _ = new Foo (); // dummy object for ApplyHack

    public int Multiply (int j) {
        return i * j;
    }
    public int Add (int j) {
        return i + j;
    }
}
class Program {
    static void Main (string [] args) {
        var foo = new Foo { i = 7 };
        Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Multiply, 5));
        Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Add, 5));
        Console.ReadKey ();
    }
}

您看,我已经找到了唯一的解决方法是,比较难看,也许慢

You see, the only workaround I've found is rather ugly and probably slow.

以你的现有代码:

public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
    return (int) method.Method.Invoke (obj, new object [] { j });
}

您可以做这样的事情:

public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
    var func = (Func<int,int>)Delegate.CreateDelegate(typeof(Func<int,int>), obj, method.Method);

    return func(j);
}

这将创建一个围绕的方法和新的对象一个新的委托。把你的第一个例子:

This will create a new delegate around the method and the new object. To take your first example:

public static int Apply (Foo obj, ???? method, int j) {
    return obj.method (j);
}

您正在寻找的类型是的System.Reflection .MethodInfo ,它是这样的:

The type you are looking for is System.Reflection.MethodInfo and it would look like this:

public static int Apply (Foo obj, MethodInfo method, int j) {
    var func = (Func<int,int>)Delegate.CreateDelegate(typeof(Func<int,int>), obj, method);

    return func(i);
}

请注意,当你在每次调用分配的代表,我相信这将仍比使用反射更快,因为你不必Box功能的输入/输出,也将其存储在 [对象] 数组。

Note that while you are allocating delegates for each invocation, I believe this will still be faster than using reflection, since you do not have to box function input/output, nor store it in object[] arrays.