我正在尝试使用postharp修改异步方法的返回值。是否可以在不知道T的情况下在运行时获取Task的结果?
即
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 ...)
}
答案 0 :(得分:1)
如果没有反思,您需要使用和界面。同样使用PostSharp 5.0,您可以使用OnSuccess
方法而不是Task<>
获取结果。
此示例适用于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};
}
}
}