How to convert delegate to object in C#?

2019-07-20 08:20发布

I am using reflection class to invoke some methods which are on the some other dll. And one of the methods' parameters are type of delegate.

And I want to invoke this methods by using reflection. So I need to pass function parameters as object array, but I could not find anything about how to convert delegate to object.

Thanks in advance

5条回答
虎瘦雄心在
2楼-- · 2019-07-20 08:41

I think this blog post:

C# Reflection - Dealing with Remote Objects

answers your question perfectly.

查看更多
时光不老,我们不散
3楼-- · 2019-07-20 08:47

Here's an example:

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 });
    }
}
查看更多
Root(大扎)
4楼-- · 2019-07-20 08:48

you can see a delegate as variable type "function". the delegate describes the parameters and return value for a matching function.

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

the above example allows 'Foo' to be used as a data type, the only allowed object that can be matched with a variable of type Foo data type is a method with the same signature so:

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.

Once you have assigned a method to a delegate, you can invoke the method via the delegate:

int n = 1;
D( n );      // or D.Invoke( n );
查看更多
劳资没心,怎么记你
5楼-- · 2019-07-20 08:49

A delegate is an object. Just create the expected delegate as you would normally, and pass it in the parameters array. Here is a rather contrived example:

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);
}
查看更多
叛逆
6楼-- · 2019-07-20 08:51

Instances of delegates are objects, so this code works (C#3 style) :

Predicate<int> p = (i)=> i >= 42;

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

Hope it helps !

Cédric

查看更多
登录 后发表回答