代码检查:不支持访问托管方法。
此检查会识别在 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] 特性的方法或作业中时,此检查才会触发。
示例
在此示例中,在 Burst 编译的作业内部对整数调用了 ToString() 和 GetType() 方法。 这些调用不受支持,并且会被标记。
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日