如何检查 Class 是否由编译器生成

How to check if Class is Compiler Generated

我想要一种方法来检查类型是否是由 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)));
        }
    }

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

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

Remarks

Apply the CompilerGeneratedAttribute attribute to any application element to indicate that the element is generated by a compiler.

Use the CompilerGeneratedAttribute attribute to determine whether an element is added by a compiler or authored directly in source code.

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

using System.Reflection;

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