Question

J'ai un cache basé sur

Dictionary<MethodBase, string>

La clé est rendue à partir MethodBase.GetCurrentMethod. Tout fonctionnait bien jusqu'à ce que les méthodes ont été explicitement déclarées. Mais un jour, il est apparu que:

Method1<T>(string value)

Makes même entrée dans le dictionnaire lorsque T obtient types tout à fait différents.

Alors, ma question est de mieux à la valeur de cache pour les méthodes génériques. (Bien sûr, je peux fournir wrapper qui fournit getCache et l'égalité rencontré des types génériques, mais cette façon ne semble pas élégant).

Mise à jour Voici ce que je veux exactement:

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);
}
Était-ce utile?

La solution

Utilisez MakeGenericMethod , si vous le pouvez :

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

Autres conseils

Ceci est impossible; une méthode générique a un seul MethodBase; il n'a pas un MethodBase par série d'arguments génériques.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top