1

如何获取拦截方法的返回类型?我正在编写一个方法级别的缓存机制,我想使用 postsharp 来拦截方法调用。但是,我需要能够将存储的对象转换为原始方法类型。

 public override void OnEntry(MethodExecutionArgs InterceptedItem)
    {
        if (_instance==null)
            _instance = new CouchbaseClient();



        string Key = GetCacheKey(InterceptedItem);


        var CacheItem = _instance.Get(Key);

        if (CacheItem != null)
        {
            // The value was found in cache. Don't execute the method. Return immediately.
            //string StringType = (String)_instance.Get(Key+"Type");
            JavaScriptSerializer jss = new JavaScriptSerializer();
            InterceptedItem.ReturnValue = jss.Deserialize<Object>(CacheItem.ToString());
            //Type Type = Type.GetType(StringType);
            InterceptedItem.ReturnValue = (Object)InterceptedItem.ReturnValue;
               // jss.Deserialize(CacheItem.ToString(), Type.GetType(StringType));
            InterceptedItem.FlowBehavior = FlowBehavior.Return;
        }
        else
        {
            // The value was NOT found in cache. Continue with method execution, but store 
            // the cache key so that we don't have to compute it in OnSuccess.
            InterceptedItem.MethodExecutionTag = Key;
        }
    }
4

1 回答 1

2

而不是使用

InterceptedItem.ReturnValue = jss.Deserialize<Object>(CacheItem.ToString());

您可以使用以下代码,允许在运行时指定对象的类型(泛型类型参数在设计时确定):

var mthInfo = InterceptedItem.Method as MethodInfo;
if (mthInfo != null)
    InterceptedItem.ReturnValue = jss.Deserialize(CacheItem.ToString(), mthInfo.ReturnType);
else
    InterceptedItem.ReturnValue = null;

您可以使用 的属性检索MethodBase对象。但是, as也用于没有返回类型的方法(例如在 a 的情况下),您需要将其强制转换为 a以便能够访问返回类型。MethodMethodExecutionArgsMethodBaseConstructorInfoMethodInfo

于 2014-04-21T08:08:39.830 回答