Como distinguir o métodobase em genéricos
-
20-09-2019 - |
Pergunta
Eu tenho um cache baseado em
Dictionary<MethodBase, string>
A chave é renderizada do MethodBase.getCurrentMethod. Tudo funcionou bem até que os métodos fossem explicitamente declarados. Mas um dia parece que:
Method1<T>(string value)
Faz a mesma entrada no dicionário quando T recebe tipos absolutamente diferentes.
Portanto, minha pergunta é sobre melhor maneira de armazenar em cache o valor para métodos genéricos. (É claro que posso fornecer o invólucro que fornece tipos genéricos de getCache e igualdade, mas dessa maneira não parece elegante).
AtualizarAqui o que eu exatamente quero:
static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>();
static void Method1<T>(T g)
{
MethodBase m1 = MethodBase.GetCurrentMethod();
cache[m1] = "m1:" + typeof(T);
}
public static void Main(string[] args)
{
Method1("qwe");
Method1<Stream>(null);
Console.WriteLine("===Here MUST be exactly 2 entry, but only 1 appears==");
foreach(KeyValuePair<MethodBase, string> kv in cache)
Console.WriteLine("{0}--{1}", kv.Key, kv.Value);
}
Solução
Usar MakeGenericMethod, se você puder:
using System;
using System.Collections.Generic;
using System.Reflection;
class Program
{
static Dictionary<MethodBase, string> cache = new Dictionary<MethodBase, string>();
static void Main()
{
Method1(default(int));
Method1(default(string));
Console.ReadLine();
}
static void Method1<T>(T g)
{
var m1 = (MethodInfo)MethodBase.GetCurrentMethod();
var genericM1 = m1.MakeGenericMethod(typeof(T)); // <-- This distinguishes the generic types
cache[genericM1] = "m1:" + typeof(T);
}
}
Outras dicas
Isso não é possível; Um método genérico possui uma única base de método; Ele não possui uma base de método por conjunto de argumentos genéricos.