2009-10-26 10 views
6

Mi rendo conto che il titolo deve essere letto più di una volta per capire ... :)Come posso passare un metodo acquisito da reflection in C# a un metodo che accetta il metodo come delegato?

Ho implementato un attributo personalizzato che applico ai metodi nelle mie classi. tutti i metodi che applicare l'attributo di avere la stessa firma e quindi ho definito un delegato per loro:

public delegate void TestMethod(); 

ho una struct che accetta che delegato come parametro

struct TestMetaData 
{ 
    TestMethod method; 
    string testName; 
} 

E 'possibile ottenere dalla riflessione un metodo che ha l'attributo personalizzato e passarlo alla struct nel membro 'metodo'?

So che puoi invocarlo ma penso che la riflessione non mi fornirà il metodo effettivo della mia classe che posso trasmettere al delegato TestMethod.

risposta

11

Una volta che avete MethodInfo tramite Reflection, potete usare Delegate.CreateDelegate per trasformarlo in Delegato, e quindi usare Reflection per impostarlo direttamente sulla proprietà/campo della vostra struct.

+0

grazie! ha funzionato perfettamente – thedrs

1

È possibile creare un delegato che chiama il metodo riflesso in fase di esecuzione utilizzando Invoke o Delegate.CreateDelegate.

Esempio:

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 sarebbe più semplice ... no Invoke lì. –

+0

@Marc, hai ragione, ho aggiornato con un esempio utilizzando CreateDelegate. – driis

0

Inoltre è necessario delegato adatto ad essere già dichiarata

0

Per fare un esempio:

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