Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a method acquired by reflection in C# to a method that accepts the method as a delegate?

I realize the title needs to be read more than once for understanding ... :)

I implemented a custom attribute that i apply to methods in my classes. all methods i apply the attribute to have the same signature and thus i defined a delegate for them:

public delegate void TestMethod();

I have a struct that accepts that delegate as a parameter

struct TestMetaData
{
  TestMethod method;
  string testName;
}

Is it possible to get from reflection a method that has the custom attribute and pass it to the struct into the 'method' member ?

I know you can invoke it but i think reflection won't give me the actual method from my class that i can cast to the TestMethod delegate.

like image 876
thedrs Avatar asked Oct 26 '09 17:10

thedrs


2 Answers

Once you have the MethodInfo via Reflection, you can use Delegate.CreateDelegate to turn it into a Delegate, and then use Reflection to set this directly to the property/field of your struct.

like image 83
Reed Copsey Avatar answered Nov 15 '22 12:11

Reed Copsey


You can create a delegate that calls your reflected method at runtime using Invoke, or Delegate.CreateDelegate.

Example:

using System;
class Program
{
    public delegate void TestMethod();
    public class Test
    {
        public void MyMethod()
        {
            Console.WriteLine("Test");
        }
    }
    static void Main(string[] args)
    {
        Test t = new Test();
        Type test = t.GetType();
        var reflectedMethod = test.GetMethod("MyMethod");
        TestMethod method = (TestMethod)Delegate.CreateDelegate(typeof(TestMethod), t, reflectedMethod);
        method();
    }
}
like image 25
driis Avatar answered Nov 15 '22 11:11

driis