2014-04-21 4 views
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; 
     } 
    } 
+0

코드를 표시하십시오. 지금까지 뭐 해봤 어? 코드의 어느 시점에서 캐싱 된 객체를 캐스팅해야합니까? – Markus

+0

InterceptedItem.ReturnValue = jss.Deserialize (CacheItem.ToString()); – CodeMilian

+0

jss.Deserialize (CacheItem.ToString());의'Object'가 문제입니까? 왜 객체를 캐시에 JSON 문자열로 저장합니까? 캐시에 객체를 넣고 직렬화 및 직렬화를 피할 수는 없습니까? – Markus

답변

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; 

Method 속성을 MethodExecutionArgs으로 사용하여 MethodBase 개체를 검색 할 수 있습니다. 그러나 MethodBase은 반환 유형이없는 메소드 (예 : ConstructorInfo의 경우)로 사용되므로 반환 유형에 액세스하려면 MethodInfo으로 캐스트해야합니다.