如何获取截获方法的返回类型?我正在编写一个方法级别的缓存机制,我想使用postharp来拦截方法调用。但是,我需要能够将存储的对象转换为原始方法类型。
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;
}
}
答案 0 :(得分: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
的{{1}}属性检索Method
对象。但是,由于MethodExecutionArgs
也用于没有返回类型的方法(例如,在MethodBase
的情况下),您需要将其强制转换为ConstructorInfo
以便能够访问返回类型。