28

我目前在尝试从MethodInfo. 我的总体目标是查看类中的方法并为标记有特定属性的方法创建委托。我正在尝试使用CreateDelegate,但出现以下错误。

无法绑定到目标方法,因为其签名或安全透明度与委托类型的不兼容。

这是我的代码

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

2 回答 2

62

您正在尝试从实例方法创建委托,但您没有传入目标。

你可以使用:

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

...或者你可以让你的方法静态。

(如果你需要同时处理这两种方法,你需要有条件地这样做,或者null作为中间参数传入。)

于 2012-06-20T13:19:59.740 回答
2

如果委托没有目标,您需要为委托使用不同的签名。然后目标需要作为第一个参数传递

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)
    {

    }
}
于 2017-10-27T18:19:17.350 回答