使用MethodBase
,是否可以获取被调用方法的参数及其值?如何使用Reflection获取方法中的参数值?
具体来说,我试图使用反射来创建缓存键。由于每种方法及其参数列表都是独一无二的,所以我认为以此为关键是理想的。这是我在做什么:
public List<Company> GetCompanies(string city)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCity(city);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
public List<Company> GetCompanies(string city, int size)
{
string key = GetCacheKey();
var companies = _cachingService.GetCacheItem(key);
if (null == company)
{
companies = _companyRepository.GetCompaniesByCityAndSize(city, size);
AddCacheItem(key, companies);
}
return (List<Company>)companies;
}
凡GetCacheKey()
定义(大约)为:
public string GetCacheKey()
{
StackTrace stackTrace = new StackTrace();
MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();
string name = methodBase.DeclaringType.FullName;
// get values of each parameter and append to a string
string parameterVals = // How can I get the param values?
return name + parameterVals;
}
嗨安德鲁,这要求我必须每次写入每个参数的名称作为'GetCacheKey()'的参数。如果可以的话,我想避免这种情况。如果我可以动态地获取这些值,它会为我节省很多打字量。 – DaveDev 2010-11-09 12:25:22
@DaveDev:我明白你的观点。请记住,显式传递参数比使用反射快得多。 – 2010-11-09 13:43:37