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