lundi 15 mars 2021

CreateDelegate() System.ArgumentException method signature mismatch

I've been trying to use reflection to compare objects whose type is not known at compile time, and rather than calling Invoke() every time I'm trying to use CreateDelegate(). I've gotten it working thus far in a generically typed class for primitives and the like, but I've run into a brick wall with objects of type KeyValuePair<TKey,TValue>. It throws with

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

when CreateDelegate() is called even though the method signature matches the types provided to and returned from Invoke(), and I can't figure out what it is I'm doing wrong. The minimal code to reproduce the exception is below:

static void Main(string[] args)
{
    var kvp = new KeyValuePair<string, string>("test key", "test value");

    var getKeyMethod = typeof(KeyValuePair<string, string>).GetProperty("Key").GetGetMethod();
    Console.WriteLine(getKeyMethod.Invoke(kvp, null));  //works fine

    var getKey = (Func<KeyValuePair<string, string>, string>) getKeyMethod.CreateDelegate(typeof(Func<KeyValuePair<string, string>, string>));  //exception thrown here
    Console.WriteLine(getKey(kvp));  //never gets here
}

I realize the same thing is possible using expression trees, and I have gotten that working using the same exact method signature, as below:

    ParameterExpression targetExp = Expression.Parameter(typeof(KeyValuePair<string, string>), "target");
    MemberExpression propertyExp = Expression.Property(targetExp, typeof(KeyValuePair<string, string>).GetProperty("Key"));
    var getKeyMethod = Expression.Lambda<Func<KeyValuePair<string, string>, string>>(propertyExp, targetExp).Compile();

All the same, I'd like to understand just what is going wrong here (expression trees are also a bit slower, but I'm mostly just annoyed that I can't get this working).





Aucun commentaire:

Enregistrer un commentaire