如何在C#中将委托转换为对象?

4
我正在使用反射类调用其他dll上的一些方法。其中一个方法的参数是委托类型。
我希望通过反射来调用这些方法。所以我需要将函数参数作为对象数组传递,但我找不到任何关于如何将委托转换为对象的内容。
提前致谢。

你能否发布一段代码示例,以便人们可以快速准确地回复? - Ruben Bartelink
5个回答

7

代理是一个对象。只需像通常创建预期的代理一样,并将其传递给参数数组即可。这里有一个相当牵强的例子:

class Mathematician {
    public delegate int MathMethod(int a, int b);

    public int DoMaths(int a, int b, MathMethod mathMethod) {
        return mathMethod(a, b);
    }
}

[Test]
public void Test() {
    var math = new Mathematician();
    Mathematician.MathMethod addition = (a, b) => a + b;
    var method = typeof(Mathematician).GetMethod("DoMaths");
    var result = method.Invoke(math, new object[] { 1, 2, addition });
    Assert.AreEqual(3, result);
}

易如反掌,马特,我想你忘记了包含一个解释性的例子! - Ruben Bartelink

1
委托实例是对象,因此此代码有效(C#3风格):
Predicate<int> p = (i)=> i >= 42;

Object[] arrayOfObject = new object[] { p };

希望有所帮助!
Cédric

1
这是一个例子:
class Program
{
    public delegate void TestDel();

    public static void ToInvoke(TestDel testDel)
    {
        testDel();
    }

    public static void Test()
    {
        Console.WriteLine("hello world");
    }

    static void Main(string[] args)
    {
        TestDel testDel = Program.Test;
        typeof(Program).InvokeMember(
            "ToInvoke", 
            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
            null,
            null,
            new object[] { testDel });
    }
}

谢谢您的回复。 我按照您的方式尝试了,我正在传递相同的委托,该委托位于外部dll中,但是出现了奇怪的异常,提示如下: 参数异常: 类型为“namespace.class.delegate”的对象无法转换为“namespace.class.delegate”。 - AFgone

1

0

你可以将委托看作是变量类型“函数”。委托描述了匹配函数的参数和返回值。

delegate void Foo(int a);  // here a new delegate obj type Foo has been declared

上面的例子允许使用“Foo”作为数据类型,唯一允许与类型为Foo数据类型的变量匹配的对象是具有相同签名的方法,因此:

void MyFunction(int x);    

Foo D = MyFunction; // this is OK

void MyOtherFunction(string x);

Foo D = MyOtherFunction; // will yield an error since not same signature.

一旦您已将方法分配给委托,您可以通过委托调用该方法:
int n = 1;
D( n );      // or D.Invoke( n );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接