首页 > 解决方案 > 如何检查类是否是编译器生成的

问题描述

我想要一种方法来检查一个类型是否是 C# 编译器自动生成的类型(例如 Lambda 闭包、操作、嵌套方法、匿名类型等)。

目前有以下几种:

public bool IsCompilerGenerated(Type type)
{
    return type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase);
}

伴随测试:

    public class UnitTest1
    {
        class SomeInnerClass
        {

        }

        [Fact]
        public void Test()
        {
            // Arrange - Create Compiler Generated Nested Type
            var test = "test";

            void Act() => _testOutputHelper.WriteLine("Inside Action: " + test);

            // Arrange - Prevent Compiler Optimizations
            test = "";
            Act();

            var compilerGeneratedTypes = GetType().Assembly
                .GetTypes()
                .Where(x => x.Name.Contains("Display")) // Name of compiler generated class == "<>c__DisplayClass5_0"
                .ToList();

            Assert.False(IsCompilerGenerated(typeof(SomeInnerClass)));

            Assert.NotEmpty(compilerGeneratedTypes);
            Assert.All(compilerGeneratedTypes, type => Assert.True(IsCompilerGenerated(type)));
        }
    }

有没有更好的方法来检查编译器生成的类型而不是名称?

标签: c#.netreflectiontypessystem.reflection

解决方案


假设 Microsoft 遵循自己的System.Runtime.CompilerServices.CompilerGeneratedAttribute应用指南,

评论

将 CompilerGeneratedAttribute 属性应用于任何应用程序元素,以指示该元素是由编译器生成的。

使用 CompilerGeneratedAttribute 特性来确定元素是由编译器添加还是直接在源代码中创作。

您可以检查类型的 CustomAttributes 以确定该类型是否被这样装饰:

using System.Reflection;

public bool IsCompilerGenerated(Type type)
{
    return type.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() != null;
}

推荐阅读