【问题标题】:How to check if Class is Compiler Generated如何检查类是否是编译器生成的
【发布时间】:2020-05-25 03:37:47
【问题描述】:

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

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

【问题讨论】:

  • 检查类型是否有System.Runtime.CompilerServices.CompilerGeneratedAttribute类型的CustomAttribute。我还没有验证所有编译器生成的类型都是如此修饰的,但我知道闭包是并且会打赌同样适用于其他类型。
  • 这看起来很完美,看起来正是我想要的!随时发布作为答案。

标签: c# .net reflection types system.reflection


【解决方案1】:

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

备注

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

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

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

using System.Reflection;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 2016-06-30
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2013-12-02
    • 2013-11-13
    相关资源
    最近更新 更多