2010-11-09 78 views
3

使用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; 
    } 

回答

2

你为什么要使用反射?在你使用GetCacheKey方法的地方你知道参数的值。你可以指定它们:

public string GetCacheKey(params object[] parameters) 

而且使用这样的:

public List<Company> GetCompanies(string city) 
{ 
    string key = GetCacheKey(city); 
    ... 
+0

嗨安德鲁,这要求我必须每次写入每个参数的名称作为'GetCacheKey()'的参数。如果可以的话,我想避免这种情况。如果我可以动态地获取这些值,它会为我节省很多打字量。 – DaveDev 2010-11-09 12:25:22

+0

@DaveDev:我明白你的观点。请记住,显式传递参数比使用反射快得多。 – 2010-11-09 13:43:37

0

这是从方法得到的参数有很大的样品:

public static string GetParamName(System.Reflection.MethodInfo method, int index) 
{ 
    string retVal = string.Empty; 
    if (method != null && method.GetParameters().Length > index) 
     retVal = method.GetParameters()[index].Name; 
    return retVal; 
} 
+0

我想他想得到参数的**值** ...要困难得多...(不必要的) – 2010-11-09 12:18:56

+0

布拉德利是正确的 - 我想要的值。但是,我不认为这是完全没有必要的。如果我可以动态获取这些值,那么我不需要像上面的例子中所示的那样将参数添加到'GetCacheKey()'中。 – DaveDev 2010-11-09 12:27:46

0

寻找相同的答案正确。除了反思,你可以在PostSharp中编写一个方面。这将削减使用反射的任何性能影响,并且不会违反任何替代原则。

相关问题