2017-01-06 2 views
0

postsharp를 사용하려고하면 비동기 메소드의 반환 값을 수정하려고합니다. T를 모른 채 런타임에 Task 결과를 얻을 수 있습니까?T - postsharp 모름 <T> 작업 결과에 액세스

public void OnSuccess(MethodExecutionArgs args) 
{ 

var returnValue = args.ReturnValue; 

// returnType is Task<T> 
var returnType = returnValue.GetType();  

// Is it possible to access the result of the task? 

// If T was known then I could cast: 
// ((Task<T>) returnValue).ContinueWith(t => t.Result ...) 
} 
+2

을 당신이 함께 할 것으로 예상된다 어떤 결과의 * 유형 *을 모르는 우물 경우? –

+0

일부 메소드는 더티 플래그가 포함 된 객체를 반환하므로 설정하고 싶습니다 –

+1

T는 파생 된 하나의 유형일까요? 'where' 지정자를 추가하면 기본 클래스의 기능에 액세스 할 수 있습니다. – Dispersia

답변

1

반사하지 않고, 당신이 사용하고 인터페이스 할 것입니다. 또한 PostSharp 5.0에서는 Task<> 대신 OnSuccess 메소드에 결과 자체가 나타납니다.

이 예는 PostSharp 5.0에서 작동합니다

using System; 
using System.Threading.Tasks; 
using PostSharp.Aspects; 
using PostSharp.Serialization; 

namespace OnMethodBoundaryAsyncTest 
{ 
    interface IDirtiness 
    { 
     bool Dirty { get; set; } 
    } 

    class MyClassWithSomeDirtyObjects : IDirtiness 
    { 
     public bool Dirty { get; set; } 
    } 

    [PSerializable] 
    class ReportDirtinessAttribute : OnMethodBoundaryAspect 
    { 
     public override void OnSuccess(MethodExecutionArgs args) 
     { 
      IDirtiness maybeDirtyObject = args.ReturnValue as IDirtiness; 

      if (maybeDirtyObject != null) 
      { 
       string dirty = maybeDirtyObject.Dirty ? "is" : "is not"; 
       Console.WriteLine($"{maybeDirtyObject} {dirty} dirty."); 
      } 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      CreateObject(false).GetAwaiter().GetResult(); 
      CreateObject(true).GetAwaiter().GetResult(); 
     } 

     [ReportDirtiness(ApplyToStateMachine = true)] 
     static async Task<MyClassWithSomeDirtyObjects> CreateObject(bool dirty) 
     { 
      return new MyClassWithSomeDirtyObjects {Dirty = dirty}; 
     } 
    } 
}