質問

私はキャッシュに基づく

Dictionary<MethodBase, string>

キーが描画されるからMethodBase.GetCurrentMethod.またまた明示的に宣言しています。そんなある日である:

Method1<T>(string value)

このと同じ入力辞書がが違います。

このような中、私た上で質問してもキャッシュ値のクラスを提供す。(もちろんを提供できるラッパーを提供するGetCacheと平等のた汎用型が、このようなエレガント).

更新 こういった:

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);
}
役に立ちましたか?

解決

使用 MakeGenericMethod, 場合では以下の操作が可能です。

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

他のヒント

ことはできません;汎用的な方法は、単一のMethodBase;いつMethodBaseットセットの一般論争することができます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top