【问题标题】:Postsharp get intercepted method return typePostsharp 获取截获的方法返回类型
【发布时间】: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(CacheItem.ToString());
  • 我认为jss.Deserialize&lt;Object&gt;(CacheItem.ToString()); 中的Object 是问题所在吗?为什么将对象作为 JSON 字符串存储在缓存中?就不能直接把对象放到缓存里,避免序列化和反序列化吗?
  • 由于我使用的是 couchbase(NoSQL),我认为我仅限于将数据保存为 json 对象。我尝试以本机格式存储对象,但是当我这样做时,对象不会存储。我必须说我对沙发底座非常陌生,所以我可能缺少一些存储选项。

标签: c# aop postsharp aspect


【解决方案1】:

而不是使用

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;

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

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多