首页 > 解决方案 > 检测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;

我的问题是我不知道还有哪些其他编译器生成的类型以及它们出现的情况。是否有可能从我的缓存机制中排除不应排除的方法?或者换一种说法:有没有办法更具体地针对使用收益返回的方法?

标签: c#yield-returncompiler-generated

解决方案


推荐阅读