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 に答える