How to get parameter values ​​in a reflection method?

Using MethodBase, is it possible to get the parameters and their values ​​of the called method?

To be specific, I am trying to use reflection to create cache keys. Since each method and its parameter list is unique, I thought it would be ideal to use this as a key. This is what I do:

    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 is GetCacheKey()defined (approximately) 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;
    }
+3
source share
3 answers

Why do you want to use reflection? In the place where you use your method GetCacheKey, you know the parameter values. You can simply specify them:

public string GetCacheKey(params object[] parameters)

And use like this:

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

:

 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

Looking for the right answer. Besides reflection, you can write Aspect in PostSharp. This will reduce the effect of performance on the use of reflection and will not violate any substitution principles.

0
source

Source: https://habr.com/ru/post/1773820/


All Articles