c# - 如何检查类是否是编译器生成的
问题描述
我想要一种方法来检查一个类型是否是 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应用指南,
评论
将 CompilerGeneratedAttribute 属性应用于任何应用程序元素,以指示该元素是由编译器生成的。
使用 CompilerGeneratedAttribute 特性来确定元素是由编译器添加还是直接在源代码中创作。
您可以检查类型的 CustomAttributes 以确定该类型是否被这样装饰:
using System.Reflection;
public bool IsCompilerGenerated(Type type)
{
return type.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() != null;
}
推荐阅读
- python - 将 AsciiMath/MathML 转换为 SVG/PNG
- python - 如何使用 setuptools 分发特定文件?
- java - Gluon-Mobile 的 Eclipse 插件状态
- python - 使用 Django/Docker/GoogleAuth/pythonRSA 导致 RSA 密钥识别失败的字符编码
- javascript - 为什么存储在 MongoDB 中的数据没有通过使用 mustache 显示在 HTML 文件中?
- istio - 使用基于 JWT 令牌的 Istio 在 Kubernetes 中进行服务路由
- puppet - Puppet 从符号链接文件中获取内容
- javascript - 循环执行获取请求
- python - “目录名称无效”在 Windows 中使用 os.makedirs 和名为“aux”的文件夹
- twilio - 特维利奥
动词没有完成一个 20 秒的 wav 文件 非常被执行