繁体   English   中英

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

[英]Construct a Task<TResult> type to be used as return value

假设我有两种方法:

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");

因此,问题在于如何基于Context.MethodInfo.ReturnType和值构造Task<TResult>变量。


为什么要这样做是因为我想通过CachingAttribute来缓存方法的返回结果。

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

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

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

然后在用法。 当我们像这样调用Foo方法时:

var result = await Foo();

//具有caching属性,结果可以是10之类的特定值。然后,我可以将缓存功能添加到所需的任何方法中,而无需更改调用者的行为。

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

样例代码:

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM