繁体   English   中英

如何使用Reflection获取方法中的参数值?

[英]How to get the values of the parameters in a method with Reflection?

使用MethodBase ,是否可以获取被调用方法的参数及其值?

具体来说,我正在尝试使用反射来创建缓存键。 由于每个方法及其参数列表都是唯一的,我认为将它作为关键是理想的。 这就是我正在做的事情:

    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方法的位置,您可以知道参数的值。 你可以指定它们:

public string GetCacheKey(params object[] parameters)

并使用这样的:

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

寻找同样的答案吧。 除了反射,你可以在PostSharp中编写一个Aspect。 这将减少使用反射对性能的影响,并且不会违反任何替换原则。

这是从方法中获取参数的绝佳示例:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM