---
title: IL2CPP 限制
product: Unity Editor
version: '6000.0'
latest_version: '7000.0'
status: This page documents version 6000.0. The latest version is 7000.0.
canonical: https://docs.unity.com/zh-cn/engine/6000.0/manual/scripting/compilation-and-code-reload/script-compilation/backends/il2cpp/restrictions
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/compilation-and-code-reload/script-compilation/backends/il2cpp/restrictions.md
generated_at: 2026-11-20T21:11:01.794Z
locale: zh-cn
---

# IL2CPP 限制

> 了解使用 IL2CPP 作为Scripting BackendWhenON某些 AOT 平台上Apply的限制。

IL2CPP 后端有一些显著限制，部分原因是提前 (AOT) 编译的固有特性，部分原因是平台指定的限制。

## 线程##threads

Web 平台ON不支持托Managed线程。[`System.Threading`](https://learn.microsoft.com/en-us/dotnet/api/system.threading?view=net-9.0)命名空间中的大多数 API 要么执行时没有特效，要么不起作用。.NET 类的某些部分也隐式依赖ON线程。一个常见的例子是 [`System.Timers.Timer`](https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-9.0) 类，该类依赖于对线程的 ON Support。有关 Detailed 细分，请参阅 Web 平台的 [.NET API 支持](/engine/6000.0/manual/platform-specific/webgl/develop/web-dotnet-api-support.md)。

## 反射##reflection

Unity 支持 ON AOT 平台的反射。但是，如果编译器无法推断代码是通过反射使用的，则代码可能在运行时不存在。有关更多信息，请参阅[ Managed 代码剥离](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-compilation/managed-code-stripping.md)。

AOT 平台无法实现 [`System.Reflection.Emit`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit?view=net-9.0) 命名空间中的任何方法。

## 异常过滤器##exception-filters

IL2CPP 支持异常过滤器。但是，过滤器语句和`catch`代码块的执行 Order 不同，因为 IL2CPP 使用 C++ 异常来实现 Managed 异常。除非过滤器代码块写入Field，否则这种情况不会明显。

ON Mono 上，Field 写入发生在过滤器评估时间，在进入`catch`代码块之前，并以相对于 Other 过滤器的指定 Order 进行。ON IL2CPP 上，Field 写入可能会在不同时间发生，因为过滤器是模拟的。这可能导致明显的差异，例如：

* 相对于 `catch` 或 `finally` 代码块已更新的 Field。
* 存在多个个过滤器When的不同交织，可能会更改哪些更新首先可见。
* 依赖 ON 过滤器的副作用来控制`catch`或`finally`中行为的代码很少看到过时或顺序不同的值。

最佳做法是将任意状态更改移动到 `catch` 代码块（或从 `catch` 调用的 helper 函数）中以避免过滤器中的副作用，从而确保 IL2CPP 和 Mono 之间的行为一致。

## Serialization##serialization

AOT 平台可能会因为使用反射而遇到 Serialization 和反序列化问题。如果类型或方法仅通过反射作为Serialization化或反序列化的一部分使用，则 AOT 编译器器无法检测到它需要Generate类型或方法所需的代码。

## Generic类型和方法##generic-types-and-methods

对于 Generic 类型和方法，编译器必须确定使用哪个 Generic 实例，因为不同的 Generic 实例可能需要不同的代码。例如，`List<int>`的代码与`List<double>`的代码不同。但是，IL2CPP 共享引用类型用法的代码，因此对`List<object>`和`List<string>`使用相同的代码。

在以下情况下，可以引用 IL2CPP 在编译时间未查找的Generic类型和方法：

1. 在运行时新建 Generic 实例：`Activator.CreateInstance(typeof(SomeGenericType<>).MakeGenericType(someType));`
2. ON Generic 实例调用 Static 方法：`typeof(SomeGenericType<>).MakeGenericType(someType).GetMethod("AMethod").Invoke(null, null);`
3. 调用 Static Generic 方法：`typeof(SomeType).GetMethod("GenericMethod").MakeGenericMethod(someType).Invoke(null, null);`
4. 对编译时间无法推断的Generic虚拟函数的某些Calls。
5. 具有深度嵌套的 Generic 值类型的 Calls，例如 `Struct<Struct<Struct<...<Struct<int>>>>`。

为了Support这些情况，IL2CPP 会生成适用于Any类型参数的Generic代码。但是，此代码较慢，因为它无法确定类型的大小，或者它是引用类型还是值类型。如果需要确保生成更快的 Generic 方法，请执行以下操作：

* 如果 Generic 参数始终为引用类型，请添加 `where: class` 约束。然后，IL2CPP 使用引用类型共享生成Fallback方法，不会导致性性能下降。
* 如果 Generic 参数始终为值类型，请添加 `where: struct` 约束。这样可以进行一些优化，但代码仍会变慢，因为值类型可能不同大小。
* 创建名为 `UsedOnlyForAOTCodeGeneration` 的方法，并添加对希望 IL2CPP Generate 生成的 Generic 类型和方法的引用。永远不需要调用此方法。以下示例可确保为 `GenericType<MyStruct>` 生成专业化设置：

```lang-cs
public void UsedOnlyForAOTCodeGeneration()
{
    // Ensure that IL2CPP will create code for MyGenericStruct
    // using MyStruct as an argument.
    新建 GenericType<MyStruct>();

    // Ensure that IL2CPP will create code for SomeType.GenericMethod
    // using MyStruct as an argument.
    新建 SomeType().GenericMethod<MyStruct>();

	public void OnMessage<T>(T value) 
	{
		Debug.LogFormat("Message value: {0}", value);
	}

    // Include an exception so we can be sure to know if this
    // method is ever called.
    抛出 新建 InvalidOperationException(
        “此方法仅用于生成 AOT 代码。”+
        "不要在运行时调用它。");
}
```

> **Note:**
>
> 要仅编译单一、完全可共享版本的 Generic 代码，请将 **IL2CPP 代码生成**[运行设置](/engine/6000.0/manual/unity-editor/editor-settings-reference/comp-manager-group/class-player-settings.md)设置为**代码大小和版本时间优化**。这会减少生成的方法数量，减少编译时间和版本大小，但代价是运行时时性性能降低。

## 从原生代码调用 Managed 方法##calling-managed-methods-from-native-code

需要编组到 C 函数指针以便从原生代码调用的 Managed 方法 ON AOT 平台有一些限制：

* Managed 方法必须是 Static 方法。
* Managed 方法必须具有 `[MonoPInvokeCallback]` 属性。
* 如果 Managed 方法是 Generic，可能需要使用 `[MonoPInvokeCallback(Type)]` 重载来指定必须支持的通用专业化设置。如果是，类型必须是具有正确 Generic Arguments 数量的 Generic 实例。ON 方法可以有多个 `[MonoPInvokeCallback]` Attributes，如下所示：

```lang-cs
// Generates reverse P/Invoke wrappers for NameOf<long> and NameOf<int>
// Note that the types are only used to indicate the generic arguments.
[MonoPInvokeCallback(typeof(Action<long>))]
[MonoPInvokeCallback(typeof(Action<int>))]
private Static 字符串 NameOfT<T>(T Item) 
{
    return typeof(T).Name;
}
```

## 不支持的 .NET API##unsupported-.net-apis

IL2CPP 不Support以下 .NET API 和Features：

* [`MarshalAs`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshalasattribute?view=net-9.0) 和 [`FieldOffset`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.fieldoffsetattribute?view=net-9.0) Attributes 的反射。在编译时间Support这些Attributes。您应该使用它们来进行正确的[平台调用编组](https://docs.microsoft.com/en-us/dotnet/framework/interop/marshaling-data-with-platform-invoke)。
* C# [`dynamic`](https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/interop/using-type-dynamic)关键字。此关关键字需要 JIT 编译，而 IL2CPP 无法实现这一点。
* [`Marshal.Prelink`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.prelink?view=net-9.0) 或 [`Marshal.PrelinkAll`](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.prelinkall?view=net-10.0) API 方法。
* [](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process?view=net-9.0)API 方法

如果桌面平台需要这些脚本，请使用 [Mono Scripting Backend](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-compilation/backends/mono.md)。

## 其他资源##additional-resources

* [Unity .NET Features](/engine/6000.0/manual/scripting/environment-and-tools/overview-of-dot-net-in-unity.md)
