2009-12-21 6 views
2

에 MethodBase을 구별하는 방법은 캐시는 키가 MethodBase.GetCurrentMethod에서 렌더링제네릭

Dictionary<MethodBase, string> 

를 기반으로했다. 메소드가 명시 적으로 선언 될 때까지 모든 것이 잘 작동했습니다. 그러나 언젠가는 다음과 같이 나타납니다 :

Method1<T>(string value) 

T가 절대적으로 다른 유형을 가져올 때 사전에서 동일한 항목을 만듭니다.

제 질문은 제네릭 메소드의 값을 캐시하는 더 나은 방법입니다. (물론 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); 
} 
+0

당신이 형식 매개 변수의 각 세트 또는 코드 (내 대답)의 각 실제 조각에 대한 서로 다른 캐시 항목에 대해 다른 캐시 항목을 하시겠습니까? – SLaks

+1

이것은 불가능한 것 같습니다. – SLaks

답변

1

사용 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); 
    } 
} 
+0

그것은 아주 오래된 질문이지만 방금 평가할 시간을 보냈습니다. 정말 좋아 보인다! – Dewfy

1

; 일반적인 메소드는 하나의 MethodBase를 가진다; 범용 인수 세트마다 1 개의 MethodBase를 가지지 않습니다.