【发布时间】:2014-04-21 16:08:39
【问题描述】:
如何获取被拦截方法的返回类型?我正在编写一个方法级别的缓存机制,我想使用 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;
}
}
【问题讨论】:
-
请出示您的代码。你试过什么了?您需要在代码的哪一点转换缓存的对象?
-
InterceptedItem.ReturnValue = jss.Deserialize
-
我认为
jss.Deserialize<Object>(CacheItem.ToString());中的Object是问题所在吗?为什么将对象作为 JSON 字符串存储在缓存中?就不能直接把对象放到缓存里,避免序列化和反序列化吗? -
由于我使用的是 couchbase(NoSQL),我认为我仅限于将数据保存为 json 对象。我尝试以本机格式存储对象,但是当我这样做时,对象不会存储。我必须说我对沙发底座非常陌生,所以我可能缺少一些存储选项。