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

问题描述 投票:0回答:1

我希望有一种方法来检查类型是否为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# .net reflection types system.reflection
1个回答
0
投票

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

备注

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

使用CompilerGeneratedAttribute属性来确定是否元素由编译器添加或直接在源代码中编写。

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

using System.Reflection;

public bool IsCompilerGenerated(Type type)
{
    return type.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() != null;
}
© www.soinside.com 2019 - 2024. All rights reserved.