Pregunta

Tengo una memoria caché basado en

Dictionary<MethodBase, string>

La clave se representa a partir MethodBase.GetCurrentMethod. Todo funcionaba bien hasta que los métodos fueron declaradas explícitamente. Pero un día se apareció lo siguiente:

Method1<T>(string value)

Hace misma entrada en el diccionario cuando T consigue absolutamente diferentes tipos.

Así que mi pregunta es sobre la mejor manera de valor de caché de métodos genéricos. (Por supuesto que puedo proporcionar envoltorio que ofrece GetCache e igualdad encontrado tipos genéricos, pero de esta manera no se ve elegante).

Actualizar Aquí lo que yo quiero exactamente:

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);
}
¿Fue útil?

Solución

MakeGenericMethod , si es posible :

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);
    }
}

Otros consejos

Esto no es posible; un método genérico tiene una sola MethodBase; que no tiene una MethodBase por juego de argumentos genéricos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top