代码检查:在 Burst 中禁止使用 typeof
此检查会报告在由 Burst 编译器 编译的代码中使用 typeof(...) 表达式。
Burst 以高性能受限的 C# 子集为目标,不支持 typeof 表达式。 这些表达式通常意味着访问托管元数据或 System.Type 对象,在受限的 Burst 执行环境中无法使用。
运作方式
分析器会在 Burst 编译上下文中(如带有 [BurstCompile] 属性的方法或作业)监控 typeof 表达式。
无论直接使用 typeof (例如赋值给变量),还是在调用期望 System.Type 参数的 API(如 SharedStatic<T>.GetOrCreate(typeof(int)) )时间接使用,此限制均适用。
示例
在此示例中, typeof(int) 表达式被用于 Burst 编译作业的 执行 方法中。 此不受支持并会被标记。
using Unity.Burst;
using Unity.Jobs;
[BurstCompile]
public struct ExampleJob : IJob
{
public void Execute()
{
// Reported: typeof(...) is not supported in Burst
var t = typeof(int);
}
}
using Unity.Burst;
using Unity.Jobs;
[BurstCompile]
public struct ExampleJob : IJob
{
public void Execute()
{
// Move type-based logic out of Burst or use generic alternatives
var value = 0;
}
}
快速修复
此检查不提供专用的快速修复。 请手动修复,可通过从 Burst 编译代码中移除 typeof 表达式,或用 Burst 兼容的泛型或编译时替代方案进行替换。
2026年 5月 8日