---
title: 使用 PropertyVisitor 类创建属性访问者
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/object-oriented-development/properties/property-visitors-property-visitor
latest_url: https://docs.unity.com/zh-cn/engine/7000.0/manual/scripting/object-oriented-development/properties/property-visitors-property-visitor.md
generated_at: 2026-11-17T15:55:36.891Z
locale: zh-cn
---

# 使用 PropertyVisitor 类创建属性访问者

> 了解如何通过示例使用 PropertyVisitor 类建属性访问者。

此示例演示如何使用 [`PropertyVisitor`](/engine/6000.0/script-reference/unity/properties/propertyvisitor.md) 底部类来创建属性访问者。有关使用 [`IPropertyBagVisitor`](/engine/6000.0/script-reference/unity/properties/ipropertybagvisitor.md) 和 [`IPropertyVisitor`](/engine/6000.0/script-reference/unity/properties/ipropertyvisitor.md) 接口的等效示例，请参阅[使用低关卡 API 创建属性访问者](/engine/6000.0/manual/scripting/object-oriented-development/properties/property-visitors-low-level-api.md)。

## 创建数据和 Utility 类##create-data-and-utility-classes

创建一个Simple的数据类和一个Utility程序类，使用访问者访问和打印Properties性：

1. 创建以下名为 `Data` 的 C# 类及其可访问的属性：

   ```lang-cs
   using System.Collections.Generic;
   using UnityEngine;

   public class Data
   {
       public string Name = "Henry";
       public Vector2 Vec2 = Vector2.one;
       public List<Color> Colors = new List<Color> { Color.green, Color.red };
       public Dictionary<int, string> Dict = new Dictionary<int, string> { { 5, "zero" } };
   }
   ```

2. 创建以下名为 `DebugUtilities` 的 Utility 类：

   ```lang-cs
   using UnityEngine;

   public static class DebugUtilities
   {
       public static void PrintObjectDump<T>(T value)
       {
       // Magic goes here.
       }
   }
   ```

## 创建访问者##create-the-visitor

按如下方式创建访问者类：

1. 创建继承自 [`PropertyVisitor`](/engine/6000.0/script-reference/unity/properties/propertyvisitor.md) 的名为 `ObjectVisitor` 的类。

2. 向类添加 [`StringBuilder`](https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=net-7.0) Field。此版本可用于表示 Object 当前状态的字符串。

3. 添加清除`StringBuilder`并重置缩进关卡的`Reset`方法。

4. 添加一个`GetDump`方法，返回对象当前状态的字符串表示。

   `ObjectVisitor` 类现在如下所示：

   ```lang-cs
   // `PropertyVisitor` is an abstract class that you must derive from. 
   public class ObjectVisitor:PropertyVisitor
   {
       private const int k_InitialIndent = 0;
       private 只读 StringBuilder m_构建器 = 新建 StringBuilder();
       
       private 整型 m_IndentLevel = k_InitialIndent;
       
       private 字符串 Indent => 新建 (' ', m_IndentLevel * 2);
       
       public void Reset()
       {
           m_Builder.Clear();
           m_IndentLevel = k_InitialIndent;
       }

       public string GetDump()
       {
           return m_Builder.ToString();
       }
   }
   ```

## 获取顶级属性##get-the-top-level-properties

在 `ObjectVisitor` 类中，重载 [`VisitProperty`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitproperty.md) 方法以访问 Object 的每个属性并日志记录属性 Name。该[`PropertyVisitor`](/engine/6000.0/script-reference/unity/properties/propertyvisitor.md)不需要 Any 成员来实现，默认情况下，它只是访问每个属性而不执行任何 Action。

1. 在 `ObjectVisitor` 类中，添加以下重载`VisitProperty`方法：

   ```lang-cs
   protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
   {
       m_Builder.AppendLine($"- {property.Name}");
   }
   ```

2. 现在有了最少的访问者，就可以实现 Utility 方法。更新 `DebugUtilities` 类中的 `PrintObjectDump` 方法以创建新的`ObjectVisitor`实例并使用它访问给定对象的 Properties：

   ```lang-cs
   public static class DebugUtilities
   {
       private Static 只读 ObjectVisitor s_Visitor = 新建();
       
       public static void PrintObjectDump<T>(T value)
       {
           s_Visitor.Reset();
           
           // This is the main entry point to run a visitor.
           PropertyContainer.Accept(s_Visitor, ref value);
           Debug.Log(s_Visitor.GetDump());
       }
   }
   ```

3. 从代码的适当位置调用 `PrintObjectDump` 方法并向其通道一个 `Data` Object。例如，从 Simple MonoBehaviour 组件中，这可能如下所示：

   ```lang-cs
   using UnityEngine;

   public class MyMonoBehaviour :MonoBehaviour
   {

       void Start()
       {
       DebugUtilities.PrintObjectDump(new Data());
       }

   }
   ```

   这会将以下输出打印到控制台：

   ```lang-text
   "name":
   - Vec2
   - 颜色
   - Dict
   ```

## 获取子属性##get-the-sub-properties

如上一部分的输出所示，重载 [`VisitProperty`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitproperty.md) 方法时，它不会自动访问对象的子 Properties。要获取子 Properties，请使用 [`PropertyContainer.Accept`](/engine/6000.0/script-reference/unity/properties/propertycontainer/accept.md) 方法以递归方式将访问器应用于每个值。

在 `ObjectVisitor` 类中，更新 `VisitProperty` 方法以递归方式将访问者应用于要嵌套的值：

```lang-cs
protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
{
    m_Builder.AppendLine($"{Indent}- {property.Name}");
        
    ++m_IndentLevel;
    // Apply this visitor recursively on the value to nest in.
    if (null != value)
        PropertyContainer.Accept(this, ref value);
    --m_IndentLevel;
}
```

控制台输出在如下所示：

```lang-text
"name":
- Vec2
x
y
- 颜色
- 0
    -R
    g：
    - b
    A
- 1
    -R
    g：
    - b
    A 
- Dict
- 5
    key
    "value": "",
```

## 显示有关每个属性的更多信息##display-more-information-about-each-property

要进一步增强打印输出，请获取Collection项的属性Name以及每个属性的类型值。某些Properties具有特殊的名称，尤其是WheCollectionollection。属性名称的约定如下：

* 对于列表项，Name 对应于索引。
* 对于字典，Name派生键值的字字符串版本。
* 对于集，Name基ON值的字字符串版本。

为了make区别更加显式，请将属性Name称括在方括号中。

1. 在 `ObjectVisitor` 类中，添加以下方法：

   ```lang-cs
   private Static 字符串 GetPropertyName(IProperty 属性)
   {
       return property switch
       {
           // You can also treat `IListElementProperty`、`IDictionaryElementProperty` 和 `ISetElementProperty` 分开。
           ICollectionElementProperty => $"[{property.Name}]",
           _ => property.Name
       };
   }
   ```

2. 更新 `VisitProperty` 方法以使用[`TypeUtility.GetTypeDisplayName`](/engine/6000.0/script-reference/unity/properties/typeutility/gettypedisplayname.md)检索给定类型的 Display Name。

   ```lang-cs
   protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
   {
       var propertyName = GetPropertyName(property);
       
       // Get the concrete type of the property or its declared type if value is null.
       var typeName = TypeUtility.GetTypeDisplayName(value?.GetType() ?? property.DeclaredValueType());
       
       m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}");
       
       ++m_IndentLevel;
       if (null != value)
           PropertyContainer.Accept(this, ref value);
       --m_IndentLevel;
   }
   ```

   控制台输出在如下所示：

   ```lang-text
   - Name = {字符串} Henry
   - Vec2 = 二维向量 (1.00, 1.00)
   - x = {float} 1
   - y = {float} 1
   - Colors = <Color> System.Collections.Generic.列表`1[UnityEngine.Color]
   - [1] = {Color} RGBA(0.000, 1.000, 0.000, 1.000)
       - r = {float} 0
       - g = {float} 1
       - b = {float} 0
       - a = {float} 1
   - [1] = {Color} RGBA(1.000, 0.000, 0.000, 1.000)
       - r = {float} 1
       - g = {float} 0
       - b = {float} 0
       - a = {float} 1
   - Dict = {Dictionary<int, string>} System.Collections.Generic.Dictionary`2[System.Int32,System.字符串]
   - [5] = {KeyValuePair<int, string>} [5, five]
       - Key = {int} 5
       - 值 = {string} 五
   ```

## 显示有关 Collection 类型的较少信息##display-less-information-for-collection-types

由于 `List<T>` 不会重载 `ToString()` 方法，因此列表值显示为 `System.Collections.Generic.List1[UnityEngine.Color]`。要减少显示的信息量，请更新`VisitProperty`以使用 [`TypeTraits.IsContainer`](/engine/6000.0/script-reference/unity/properties/typetraits/iscontainer.md) Utility 方法仅显示不包含子 Properties 的类型（例如图元、枚举和字符串）的值。

在 `ObjectVisitor` 类中，更新 `VisitProperty` 方法以使用[`TypeTraits.IsContainer`](/engine/6000.0/script-reference/unity/properties/typetraits/iscontainer.md)确定该值是否为容器类型。如果是，则显示不带 值的类型 Name。否则，显示类型 Name 和 值：

```lang-cs
protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
{
    var propertyName = GetPropertyName(property);

    var type = value?.GetType() ?? property.DeclaredValueType();
    var typeName = TypeUtility.GetTypeDisplayName(type);
    
    // Only display the values for primitives, enums and strings.
    if (TypeTraits.IsContainer(type))
        m_Builder.AppendLine($"{Indent}- {propertyName} {{{typeName}}}");
    else
        m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}");
    
    ++m_IndentLevel;
    if (null != value)
        PropertyContainer.Accept(this, ref value);
    --m_IndentLevel;
}
```

控制台输出在如下所示：

```lang-text
- Name = {字符串} Henry
- Vec2 二维向量}
- x = {float} 1
- y = {float} 1
- 颜色<Color>
**颜色**
    - r = {float} 0
    - g = {float} 1
    - b = {float} 0
    - a = {float} 1
**颜色**
    - r = {float} 1
    - g = {float} 0
    - b = {float} 0
    - a = {float} 1
- Dict {Dictionary<int, string>
- [5] {KeyValuePair<int, string>}
    - Key = {int} 5
    - 值 = {string} 五
```

> **Tip:**
>
> 为了减少显示的信息量，还可以使用以下方法重载 Collection 类型的`Visit`专用化：

* [`PropertyVisitor.VisitCollection`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitcollection.md)
* [`PropertyVisitor.VisitList`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitlist.md)
* [`PropertyVisitor.VisitDictionary`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitdictionary.md)
* [`PropertyVisitor.VisitSet`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitset.md)

这些与 [`VisitProperty`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitproperty.md) 方法类似，但它们公开了各自 Collections 类型的 Generic Parameters。

## 添加指定的类型覆盖##add-type-specific-overrides

添加指定的类型覆盖以更紧凑的方式显示[`Vector2`](/engine/6000.0/script-reference/unityengine/vector2.md)和[`Color`](/engine/6000.0/script-reference/unityengine/color.md)类型。

将 [`PropertyVisitor`](/engine/6000.0/script-reference/unity/properties/propertyvisitor.md) 与 [`IVisitPropertyAdapter`](/engine/6000.0/script-reference/unity/properties/ivisitpropertyadapter.md) 一起使用。当为指定类型注册适配器时，如果在访问期间遇到目标类型，则会调用适配器而不是 [`VisitProperty`](/engine/6000.0/script-reference/unity/properties/propertyvisitor/visitproperty.md) 方法。

在 `ObjectVisitor` 类中，添加 `Vector2` 和 `Color` 的`IVisitPropertyAdapter`：

```lang-cs
public class DumpObjectVisitor
    PropertyVisitor
    , IVisitPropertyAdapter<Vector2>
    , IVisitPropertyAdapter<Color>
{
    public DumpObjectVisitor()
    {
        AddAdapter(this);
    }
    
    void IVisitPropertyAdapter<Vector2>.Visit<TContainer>(in VisitContext<TContainer, Vector2> context, ref TContainer container, ref Vector2 value)
    {
        var propertyName = GetPropertyName(context.Property);
        m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Vector2)}}} {value}");
    }

    void IVisitPropertyAdapter<Color>.Visit<TContainer>(in VisitContext<TContainer, Color> context, ref TContainer container, ref Color value)
    {
        var propertyName = GetPropertyName(context.Property);
        m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Color)}}} {value}");
    }
}
```

## 开始访问子属性##start-visitation-on-sub-properties

当您运行 ON 数据访问者时，默认情况下，它会启动顶部关卡对象的访问。对于 Any 属性访问者，要开始访问对象的子 Properties，请向 [`PropertyContainer.Accept`](/engine/6000.0/script-reference/unity/properties/propertycontainer/accept.md) 方法通道[`PropertyPath`](/engine/6000.0/script-reference/unity/properties/propertypath.md)。

1. 更新`DebugUtilities`方法以采取可选`PropertyPath`：

   ```lang-csharp
   public static class DebugUtilities
   {
       private Static 只读 ObjectVisitor s_Visitor = 新建();

       public static void PrintObjectDump<T>(T value, PropertyPath path = default)
       {
           s_Visitor.Reset();
           if (path.IsEmpty)
               PropertyContainer.Accept(s_Visitor, ref value);
           else
               PropertyContainer.Accept(s_Visitor, ref value, path);
           Debug.Log(s_Visitor.GetDump());
       }
   }
   ```

2. 使用 `Data` Object 调用 `PrintObjectDump` 方法。控制台输出在如下所示：

   ```lang-text
   - Name { string} = Henry
   - Vec2 二维向量 = (1.00, 1.00)
   - 颜色<Color>
     - [0] = {颜色} RGBA(0.000, 1.000, 0.000, 1.000)
     - [1] = {颜色} RGBA(1.000, 0.000, 0.000, 1.000)
   - Dict {Dictionary<int, string>
     - [5] {KeyValuePair<int, string>}
       - Key {int} = 5
       - 值 { string} = 五个
   ```

## 完整的访客代码##complete-visitor-code

访问者类的完整代码现在如下所示：

```cs
using System.Text;
    using Unity.Properties;
    using UnityEngine;

    public class ObjectVisitor
    PropertyVisitor
    , IVisitPropertyAdapter<Vector2>
    , IVisitPropertyAdapter<Color>
    {
        private const int k_InitialIndent = 0;

        // StringBuilder to store the dumped object's properties and values.
        private 只读 StringBuilder m_构建器 = 新建 StringBuilder();
        private 整型 m_IndentLevel = k_InitialIndent;

        // Helper property to get the current indentation.
        private 字符串 Indent => 新建(' ', m_IndentLevel * 2);

        public ObjectVisitor()
        {
            // Constructor, it initializes the ObjectVisitor and adds itself as an adapter
            // to handle properties of type Vector2 and Color.
            AddAdapter(this);
        }

        // Reset the visitor, clearing the StringBuilder and setting indentation to initial level.
        public void Reset()
        {
            m_Builder.Clear();
            m_IndentLevel = k_InitialIndent;
        }

        // Get the string representation of the dumped object.
        public string GetDump()
        {
            return m_Builder.ToString();
        }

        // Helper method to get the property name, handling collections and other property types.
        private Static 字符串 GetPropertyName(IProperty 属性)
        {
            return property switch
            {
                // If it's a collection element property, display it with brackets
                ICollectionElementProperty => $"[{property.Name}]",
                // For other property types, display the name as it is
                _ => property.Name
            };
        }

        // This method is called when visiting each property of an object.
        // It determines the type of the value and formats it accordingly for display.
        protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
        {
            var propertyName = GetPropertyName(property);

            // Get the type of the value or property.
            var type = value?.GetType() ?? property.DeclaredValueType();
            var typeName = TypeUtility.GetTypeDisplayName(type);

            // Only display the values for primitives, enums, and strings, and treat other types as containers.
            if (TypeTraits.IsContainer(type))
                m_Builder.AppendLine($"{Indent}- {propertyName} {{{typeName}}}");
            else
                m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}");

            // Increase indentation level before visiting child properties (if any).
            ++m_IndentLevel;
            if (null != value)
                PropertyContainer.Accept(this, ref value);
            // Decrease indentation level after visiting child properties.
            --m_IndentLevel;
        }
        
        // This method is a specialized override for Vector2 properties.
        // It displays the property name and its value as a Vector2.
        void IVisitPropertyAdapter<Vector2>.Visit<TContainer>(in VisitContext<TContainer, Vector2> context, ref TContainer container, ref Vector2 value)
        {
            var propertyName = GetPropertyName(context.Property);
            m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Vector2)}}} {value}");
        }

        // This method is a specialized override for Color properties.
        // It displays the property name and its value as a Color.
        void IVisitPropertyAdapter<Color>.Visit<TContainer>(in VisitContext<TContainer, Color> context, ref TContainer container, ref Color value)
        {
            var propertyName = GetPropertyName(context.Property);
            m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Color)}}} {value}");
        }
       
    }
```

## 其他资源##additional-resources

* [属性访问者](/engine/6000.0/manual/scripting/object-oriented-development/properties/property-visitors.md)
* [属性包](/engine/6000.0/manual/scripting/object-oriented-development/properties/property-bags.md)
* [属性路径](/engine/6000.0/manual/scripting/object-oriented-development/properties/property-paths.md)
* [使用低关卡 API 创建属性访问者](/engine/6000.0/manual/scripting/object-oriented-development/properties/property-visitors-low-level-api.md)
