代码检查:不支持访问托管方法。
此检查会识别在由 Burst 编译器 编译的上下文中对托管方法(通常属于 System.Object 或 System.ValueType )的调用。 由于 Burst 只支持 C# 的高性能受限子集,因此不支持涉及装箱、引用类型或其他托管行为的方法。
运作方式
分析器会监控 Burst 编译代码中的方法调用(IInvocationExpression)。 分析器会根据以下规则判断调用是否被禁止:
禁止:直接属于
System.Object(例如ToString、GetType、Equals)或System.ValueType的方法通常被禁止,因为它们通常需要装箱或与托管堆交互。例外(GetHashCode):在结构体中,仅当调用
GetHashCode不产生装箱时才允许。 在重写它的结构体中调用base.GetHashCode(),如果到达托管实现,仍然存在问题。重写:如果结构体重写类似
Equals(object)的方法,并在 Burst 内调用,则被禁止,因为object参数本身会导致装箱。
只有当代码位于带有 [BurstCompile] 属性的方法或作业中时,此检查才会触发。
示例
在本例中, ToString() 和 GetType() 方法在 Burst 编译的作业中被调用在一个整数上。 这些调用不被支持,并会被标记。
using Unity.Burst;
using Unity.Jobs;
using UnityEngine;
[BurstCompile]
public struct MyJob : IJob
{
public int value;
public void Execute()
{
// Reported: Accessing a managed method 'ToString' is not supported
string s = value.ToString();
// Reported: Accessing a managed method 'GetType' is not supported
var type = GetType();
}
}
using Unity.Burst;
using Unity.Jobs;
[BurstCompile]
public struct MyJob : IJob
{
public int value;
public void Execute()
{
// Avoid managed methods; perform operations using blittable types
int result = value * 2;
}
}
2026年 5月 8日