Mic*_*han 1 .net c# reflection types system.reflection
我想要一种方法来检查类型是否是 C# 编译器自动生成的类型(例如 Lambda 闭包、操作、嵌套方法、匿名类型等)。
目前有以下几点:
public bool IsCompilerGenerated(Type type)
{
return type.Name.StartsWith("<>", StringComparison.OrdinalIgnoreCase);
}
Run Code Online (Sandbox Code Playgroud)
附带测试:
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)));
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来检查编译器生成的类型而不是名称?
假设 Microsoft 遵循他们自己的System.Runtime.CompilerServices.CompilerGeneratedAttribute应用指南,
评论
将 CompilerGeneratedAttribute 属性应用于任何应用程序元素,以指示该元素是由编译器生成的。
使用 CompilerGeneratedAttribute 属性来确定元素是由编译器添加还是直接在源代码中创作。
您可以检查该类型的 CustomAttributes 以确定该类型是否使用以下内容进行装饰:
using System.Reflection;
public bool IsCompilerGenerated(Type type)
{
return type.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() != null;
}
Run Code Online (Sandbox Code Playgroud)