c# - 检测C#方法是否使用yield return
问题描述
我正在尝试编写一个简单的缓存机制。基本上,每当调用一个方法时,它的返回值都应该保存在缓存中。使用AOP,我的简化 CacheAspect 如下所示。
using Castle.DynamicProxy;
public class CacheAspect : IInterceptor
{
private object cache;
public void Intercept(IInvocation invocation)
{
if (cache is null)
{
invocation.Proceed();
cache = invocation.ReturnValue;
return;
}
invocation.ReturnValue = cache;
}
}
但是,当切面截获使用yield return的方法时,它只缓存编译器生成的状态机,而不是物化结果。因此,在这种情况下,我希望方面能够快速失败。
因此,我想从方法的返回值中扣除它是否使用收益返回。到目前为止,我只找到了可以完成工作的解决方案。
private static bool IsReturnTypeCompilerGenerated(IInvocation invocation) =>
invocation
.ReturnValue
.GetType()
.GetCustomAttribute(typeof(CompilerGeneratedAttribute), inherit: true)
is object;
我的问题是我不知道还有哪些其他编译器生成的类型以及它们出现的情况。是否有可能从我的缓存机制中排除不应排除的方法?或者换一种说法:有没有办法更具体地针对使用收益返回的方法?
解决方案
推荐阅读
- python - 如何从 func1 中获取 var1 并在 func2 中使用它而不在 func1 中运行两次
- c - 使用 mmap 读取/写入文件时如何解析 ENODEV
- python - ',' 在这个切片操作中做了什么 - [:,::-1]
- c# - 在可视化树中添加和删除用户控件会引发 Unloaded 事件,但不会引发 Loaded 事件
- swift - 是否有更可定制的方式来创建嵌入式超链接?
- sql - 个人和团体帐户的数据库模式(如 Facebook 用户和页面)
- javascript - window.move 在负方向问题
- c++ - 如何降低高分辨率(10 微秒)精确计时器的 CPU 使用率?
- python - 向量化 Numpy 3D 和 2D 数组操作
- swift - 如何使用 Swift 和 AppKit (Xcode for MacOS) 获取 IOBluetoothDevice 的电池电量