简体   繁体   中英

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

Using MethodBase , is it possible to get the parameters and their values of the method that's being called?

To be specific, I'm trying to use reflection to create Cache keys. As each method and its parameter list is unique, I thought it'd be ideal to use this as the key. This is what I'm doing:

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

Where GetCacheKey() is defined (roughly) as:

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

Why do you want to use reflection? In the place where you use your GetCacheKey method you know the values of the parameters. You can just specify them:

public string GetCacheKey(params object[] parameters)

And use like this:

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

Looking for the same answer right. Besides reflection you can write an Aspect in PostSharp. This will cut any performance impact of using reflection and won't violate any substitution principles.

this is a great sample for getting parameters from a method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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