Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

589
Visualizações
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).

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

KeyValuePair<,> is a struct. There are special rules for structs and delegates. To access an instance method you essentially need a delegate with a ref parameter. For example, the following works as expected:

// define delegate
delegate string RefDel(ref KeyValuePair<string, string> kvp);

// in method 
var kvp = new KeyValuePair<string, string>("test key", "test value");

var getKeyMethod = typeof(KeyValuePair<string, string>).GetProperty("Key").GetGetMethod();
var getKey = (RefDel)getKeyMethod.CreateDelegate(typeof(RefDel));

Console.WriteLine(getKey(ref kvp));  // "test key"

See here for a live example.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda