构造<TResult>要用作返回值的任务类型



>假设我有两个方法:

public async Task<int> Foo()
{
return Datetime.Now.Second;
}
public async Task<string> Bar()
{
return "222";
}

还有一个上下文,其中包含有关方法的一些信息:

Context.ReturnValue,对于 Foo()Task<int>,对 Bar()Task<string>

Context.MethodInfo MethodInfo 用于我调用的方法。

我想做的是一些模拟的东西,比如我想根据 Context.MethodInfo.ReturnType 的类型为 Foo() 方法返回 2。

Context.ReturnValue = Task<int>.FromResult(2);

我也希望这个解决方案用于 Bar():

Context.ReturnValue = Task<string>.FromResult("333");

所以问题是Task<TResult>我如何基于 Context.MethodInfo.ReturnType and value.

我想

这样做的原因是我想通过 CachingAttribute 缓存方法的返回结果。

[CachingAttribute]    
public async Task<int> Foo(){return 1;}

此属性可以自动处理以下事项:

  1. 检查缓存提供程序中的缓存值,例如 redis。
  2. 如果存在,则处理返回值。(此问题存在此处)
  3. 如果不是,则执行该方法并将返回值放入缓存提供程序中。

然后在用法中。 当我们调用 Foo 方法时,如下所示:

var result = await Foo();

//使用缓存属性,结果可以是特定的值,如 10。然后,我可以向所需的任何方法添加缓存功能,而无需更改调用方的行为。

我已经通过使用动态关键字解决了这个问题。

示例代码:

if (context.IsAsync())
{
dynamic member = context.ServiceMethod.ReturnType.GetMember("Result")[0];
dynamic temp = System.Convert.ChangeType(result, member.PropertyType);
context.ReturnValue = System.Convert.ChangeType(Task.FromResult(temp), context.ServiceMethod.ReturnType);
}

最新更新