2012-06-20 32 views
21

Actualmente estoy teniendo un problema al tratar de crear delegados desde MethodInfo. Mi objetivo general es mirar a través de los métodos en una clase y crear delegados para aquellos marcados con cierto atributo. Estoy tratando de usar CreateDelegate pero recibo el siguiente error.Creando delegado desde MethodInfo

No se puede enlazar con el método de destino porque su firma o transparencia de seguridad no es compatible con la del tipo de delegado.

Aquí está mi código

public class TestClass 
{ 
    public delegate void TestDelagate(string test); 
    private List<TestDelagate> delagates = new List<TestDelagate>(); 

    public TestClass() 
    { 
     foreach (MethodInfo method in this.GetType().GetMethods()) 
     { 
      if (TestAttribute.IsTest(method)) 
      { 
       TestDelegate newDelegate = (TestDelagate)Delegate.CreateDelegate(typeof(TestDelagate), method); 
       delegates.Add(newDelegate); 
      } 
     } 
    } 

    [Test] 
    public void TestFunction(string test) 
    { 

    } 
} 

public class TestAttribute : Attribute 
{ 
    public static bool IsTest(MemberInfo member) 
    { 
     bool isTestAttribute = false; 

     foreach (object attribute in member.GetCustomAttributes(true)) 
     { 
      if (attribute is TestAttribute) 
       isTestAttribute = true; 
     } 

     return isTestAttribute; 
    } 
} 

Respuesta

46

Usted está tratando de crear un delegado de un métodoejemplo, pero usted no está pasando por un objetivo.

que puede usar:

Delegate.CreateDelegate(typeof(TestDelagate), this, method); 

... o usted podría hacer que su método estático.

(Si tiene que hacer frente a dos tipos de método, tendrá que hacerlo de forma condicional, o pasa en null como argumento central.)

+0

Tiene sentido, eso funciona muy bien. Acabo de mirar la descripción justo después de publicar esto y vi que decía función estática. Gracias por señalar cómo hacerlo con una instancia. – thecaptain0220

0

Se necesita una firma diferente para el delegado, si no tiene objetivo El objetivo debe pasar como el primer argumento, luego

public class TestClass 
{ 
    public delegate void TestDelagate(TestClass instance, string test); 
    private List<TestDelagate> delagates = new List<TestDelagate>(); 

    public TestClass() 
    { 
     foreach (MethodInfo method in this.GetType().GetMethods()) 
     { 
      if (TestAttribute.IsTest(method)) 
      { 
       TestDelegate newDelegate = (TestDelagate)Delegate.CreateDelegate(typeof(TestDelagate), null, method); 
       delegates.Add(newDelegate); 
       //Invocation: 
       newDelegate.DynamicInvoke(this, "hello"); 

      } 
     } 
    } 

    [Test] 
    public void TestFunction(string test) 
    { 

    } 
} 
Cuestiones relacionadas