从MethodInfo创建委托

the*_*220 26 c# attributes delegates methodinfo

我目前正在尝试从中创建委托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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 54

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

你可以使用:

Delegate.CreateDelegate(typeof(TestDelagate), this, method);
Run Code Online (Sandbox Code Playgroud)

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

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