如何区分MethodBase在仿制药 [英] How to distinguish MethodBase in generics
问题描述
我有一个基于缓存
词典< MethodBase,串>
关键是从MethodBase.GetCurrentMethod呈现。一切工作正常,直到方法进行显式声明。但是有一天它似乎:
方法1< T>(字符串值)
静静地在字典同一条目当T得到完全不同的类型。
所以我的问题是关于更好的方式来为泛型方法的缓存值。 (当然,我可以提供包装,提供GetCache和遇到的平等泛型类型,但这种方式并不显得高雅)。
更新 在这里,我到底要:
静态字典< MethodBase,串>缓存=新字典< MethodBase,串>();
静态无效的方法1< T>(T G)
{
MethodBase M1 = MethodBase.GetCurrentMethod();
缓存[M1] =M1:+的typeof(T);
}
公共静态无效的主要(字串[] args)
{
方法一(QWE);
方法1<流>(NULL);
Console.WriteLine(===这里必须正好2项,但只有1个出现==);
的foreach(KeyValuePair< MethodBase,串>千伏缓存)
Console.WriteLine({0} - {1},kv.Key,kv.Value);
}
使用的 MakeGenericMethod ,如果可以的话:
使用系统;
使用System.Collections.Generic;
使用的System.Reflection;
类节目
{
静态字典< MethodBase,串>缓存=新字典< MethodBase,串>();
静态无效的主要()
{
方法1(默认值(INT));
方法1(默认值(字符串));
到Console.ReadLine();
}
静态无效的方法1< T>(T G)
{
VAR M1 =(MethodInfo的)MethodBase.GetCurrentMethod();
VAR genericM1 = m1.MakeGenericMethod(typeof运算(T)); //< - 这区分了一般类型
缓存[genericM1] =M1:+的typeof(T);
}
}
I have a cache based on
Dictionary<MethodBase, string>
The key is rendered from MethodBase.GetCurrentMethod. Everything worked fine until methods were explicitly declared. But one day it is appeared that:
Method1<T>(string value)
Makes same entry in Dictionary when T gets absolutely different types.
So my question is about better way to cache value for generic methods. (Of course I can provide wrapper that provides GetCache and equality encountered generic types, but this way doesn't look elegant).
Update Here what I exactly want:
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);
}
Use MakeGenericMethod, if you can:
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在仿制药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!