代码检查:在 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日