Creating delegate from MethodInfo

thecaptain0220 picture thecaptain0220 · Jun 20, 2012 · Viewed 28.3k times · Source

I am currently running into an issue trying to create delegates from MethodInfo. My overall goal is to look through the methods in a class and create delegates for ones marked with a certain attribute. I am trying to use CreateDelegate but I am getting the following error.

Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

Here is my code

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

Answer

Jon Skeet picture Jon Skeet · Jun 20, 2012

You're trying to create a delegate from an instance method, but you're not passing in a target.

You could use:

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

... or you could make your method static.

(If you need to cope with both kinds of method, you'll need to do that conditionally, or pass in null as the middle argument.)