【发布时间】: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