2009-10-26 18 views
6

Me doy cuenta de que el título debe leerse más de una vez para entender ... :)¿Cómo puedo pasar un método adquirido por reflexión en C# a un método que acepta el método como delegado?

Implementé un atributo personalizado que aplico a los métodos en mis clases. todos los métodos i aplicar el atributo de tener la misma firma y por lo tanto he definido un delegado para ellos:

public delegate void TestMethod(); 

tengo una estructura que acepte que el delegado como parámetro

struct TestMetaData 
{ 
    TestMethod method; 
    string testName; 
} 

¿Es posible obtener de la reflexión un método que tiene el atributo personalizado y pasarlo a la estructura en el miembro 'método'?

Sé que puede invocarlo pero creo que el reflejo no me dará el método real de mi clase que puedo transmitir al delegado de TestMethod.

Respuesta

11

Una vez que tenga MethodInfo via Reflection, puede usar Delegate.CreateDelegate para convertirlo en Delegado, y luego usar Reflection para establecerlo directamente en la propiedad/campo de su estructura.

+0

gracias! funcionó perfectamente – thedrs

1

Puede crear un delegado que llame a su método reflejado en tiempo de ejecución utilizando Invoke o Delegate.CreateDelegate.

Ejemplo:

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(); 
    } 
} 
+0

Delegate.CreateDelegate sería más simple ... no invocar allí. –

+0

@Marc, tiene razón, actualicé con una muestra usando CreateDelegate. – driis

0

También es necesario delegado adecuado para ser declarado ya

0

A modo de ejemplo:

using System; 
using System.Linq; 

using System.Reflection; 
public delegate void TestMethod(); 
class FooAttribute : Attribute { } 
static class Program 
{ 
    static void Main() { 
     // find by attribute 
     MethodInfo method = 
      (from m in typeof(Program).GetMethods() 
      where Attribute.IsDefined(m, typeof(FooAttribute)) 
      select m).First(); 

     TestMethod del = (TestMethod)Delegate.CreateDelegate(
      typeof(TestMethod), method); 
     TestMetaData tmd = new TestMetaData(del, method.Name); 
     tmd.Bar(); 
    } 
    [Foo] 
    public static void TestImpl() { 
     Console.WriteLine("hi"); 
    } 
} 

struct TestMetaData 
{ 
    public TestMetaData(TestMethod method, string name) 
    { 
     this.method = method; 
     this.testName = name; 
    } 
    readonly TestMethod method; 
    readonly string testName; 
    public void Bar() { method(); } 
} 
Cuestiones relacionadas