---
title: 避免 C# 反射开销
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/analysis/performance-memory/managed-memory/gc-avoid-reflection
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/analysis/performance-memory/managed-memory/gc-avoid-reflection.md
last_updated: 2026-10-03
generated_at: 2026-11-21T06:34:24.366Z
locale: zh-cn
---

# 避免 C# 反射开销

> 通过在运行时时避免使用 C# 反射来减少垃圾回收器的开销。

[Mono](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-compilation/backends/mono.md) 和 [IL2CPP](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-compilation/backends/il2cpp.md) 脚本后端都在内部缓存 All C# [`System.Reflection`](https://learn.microsoft.com/en-us/dotnet/api/system.reflection?view=net-9.0) 对象，Unity 不会垃圾收集它们。这意味着垃圾回收器在应用程序程序的Lifetime周期内持续扫描缓存的 C# 反射对象，这会导致不必要且潜在的巨大垃圾回收器开销。

为了最大限度减少垃圾回收器的开销，应避免使用在运行时创建大量 C# 反射对象的方法，例如 [`Assembly.GetTypes`](https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.gettypes) 和 [`Type.GetMethods`](https://docs.microsoft.com/en-us/dotnet/api/system.type.getmethods)。相反，应在 Unity Editor 中扫描程序集以查找所需数据并将其 Serialize 或使用代码生成使数据在运行时可用。

## 在 Editor 中扫描程序集##scan-assemblies-in-the-editor

以下示例展示了如何在 Editor 中扫描程序集、Serialize 数据并在运行时使用而不进行反射。假设您想要查找实现名为 `IMyFeature` 的接口的所有类型并在运行时使用该信息。您可以编写 Editor 脚本，扫描实现 `IMyFeature` 的所有类型并将其名称保存到 `ScriptableObject` 或 json 文件，如下所示：

```lang-cs
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;

[CreateAssetMenu(menuName = "Feature/FeatureTypeList")]
public class FeatureTypeList :ScriptableObject
{
    public List<string> typeNames;
}

public static class FeatureTypeScanner
{
    [MenuItem("工具/扫描 IMyFeature Types")]
    public static void ScanTypes()
    {
        var featureType = typeof(IMyFeature);
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes())
            .Where(t => featureType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
            .Select(t => t.FullName)
            .ToList();

        // Create/overwrite the asset
        var asset = ScriptableObject.CreateInstance<FeatureTypeList>();
        asset.typeNames = types;
        AssetDatabase.CreateAsset(asset, "Assets/FeatureTypeList.asset");
        AssetDatabase.SaveAssets();

        调试。日志($"Found {types.数量} 实现 IMyFeature 的类型。保存到 FeatureTypeList.resource");
    }
}
```

从菜单中运行**工具 > 扫描 IMyFeature Types**。这将创建包含类型名称列表的`Assets/FeatureTypeList.asset`。

在运行时，可以加载此资源并使用类型名称通过 `Activator.CreateInstance` 进行实例化，或仅用于显示。如果使用代码生成器，则无需反射，如下所示：

```lang-cs
public class FeatureTypeLoader : MonoBehaviour
{
    public FeatureTypeList featureTypes;

    void Start()
    {
        var assemblyName = this.GetType().Assembly.FullName;
        Foreach（featureTypes.typeNames 中的 var typeName）
        {
            Debug.Log("Instantiating feature type: " + typeName);
            Activator.CreateInstance(assemblyName, typeName);
            // You can also use Type.GetType(typeName) (both of these still uses reflection but only on the pre-selected feature types instead of casting a wider net across all sort of types in the assembly.)
        }
    }
}
```

## 使用代码生成##use-code-generation

您可以在 Editor 时间Generate成一个包含类型或委托的StaticArray的 C# 文件，而不是存储类型名称，从而消除All运行时时反射。以下代码示例使用已发现类型的 Static Array 生成文件`Assets/GeneratedFeatureTypes.cs`，可在运行时使用而不进行反射：

```lang-cs
using UnityEditor;
using System;
using System.Linq;
using System.Text;
using System.IO;

public static class FeatureTypeCodeGen
{
    [MenuItem("Tools/CodeGen IMyFeature Types")]
    public static void CodeGenTypes()
    {
        var featureType = typeof(IMyFeature);
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes())
            .Where(t => featureType.IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract)
            .ToList();

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("public static class GeneratedFeatureTypes {");
        sb.AppendLine("    public static readonly System.Type[] Types = new System.Type[] {");
        Foreach（类型不同）
        {
            sb.AppendLine($"        typeof({t.FullName}),");
        }
        sb.AppendLine("    };");
        sb.AppendLine("}");

        File.WriteAllText("Assets/GeneratedFeatureTypes.cs", sb.ToString());
        AssetDatabase.Refresh();
        Debug.Log("Generated FeatureTypes.cs with " + types.Count + " types.");
    }
}
```

## 其他资源##additional-resources

* [Garbage Collection 模式](/engine/6000.0/manual/analysis/performance-memory/managed-memory/incremental-garbage-collection.md)
* [配置垃圾收集](/engine/6000.0/manual/analysis/performance-memory/managed-memory/disabling-garbage-collection.md)
* [针对托管内存优化代码](/engine/6000.0/manual/scripting/optimization/performance-optimizing-code-managed-memory.md)
