簡體   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