使用 PropertyVisitor 类创建属性访问者
了解如何通过示例使用 PropertyVisitor 类建属性访问者。
阅读时间12 分钟最后更新于 6 天前
此示例演示如何使用 底部类来创建属性访问者。有关使用 和 接口的等效示例,请参阅使用低关卡 API 创建属性访问者。
PropertyVisitorIPropertyBagVisitorIPropertyVisitor创建数据和 Utility 类
创建一个Simple的数据类和一个Utility程序类,使用访问者访问和打印Properties性:
-
创建以下名为的 C# 类及其可访问的属性:
Datausing 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" } };} -
创建以下名为的 Utility 类:
DebugUtilitiesusing UnityEngine;public static class DebugUtilities{ public static void PrintObjectDump<T>(T value) { // Magic goes here. }}
创建访问者
按如下方式创建访问者类:
-
创建继承自的名为
PropertyVisitor的类。ObjectVisitor -
向类添加Field。此版本可用于表示 Object 当前状态的字符串。
StringBuilder -
添加清除并重置缩进关卡的
StringBuilder方法。Reset -
添加一个方法,返回对象当前状态的字符串表示。
GetDump类现在如下所示:ObjectVisitor// `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(); }}
获取顶级属性
在 类中,重载 方法以访问 Object 的每个属性并日志记录属性 Name。该不需要 Any 成员来实现,默认情况下,它只是访问每个属性而不执行任何 Action。
ObjectVisitorVisitPropertyPropertyVisitor-
在类中,添加以下重载
ObjectVisitor方法:VisitPropertyprotected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ m_Builder.AppendLine($"- {property.Name}");} -
现在有了最少的访问者,就可以实现 Utility 方法。更新类中的
DebugUtilities方法以创建新的PrintObjectDump实例并使用它访问给定对象的 Properties:ObjectVisitorpublic 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()); }} -
从代码的适当位置调用方法并向其通道一个
PrintObjectDumpObject。例如,从 Simple MonoBehaviour 组件中,这可能如下所示:Datausing UnityEngine;public class MyMonoBehaviour :MonoBehaviour{ void Start() { DebugUtilities.PrintObjectDump(new Data()); }}这会将以下输出打印到控制台:"name":- Vec2- 颜色- Dict
获取子属性
如上一部分的输出所示,重载 方法时,它不会自动访问对象的子 Properties。要获取子 Properties,请使用 方法以递归方式将访问器应用于每个值。
VisitPropertyPropertyContainer.Accept在 类中,更新 方法以递归方式将访问者应用于要嵌套的值:
ObjectVisitorVisitPropertyprotected 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;}
控制台输出在如下所示:
"name":- Vec2xy- 颜色- 0 -R g: - b A- 1 -R g: - b A - Dict- 5 key "value": "",
显示有关每个属性的更多信息
要进一步增强打印输出,请获取Collection项的属性Name以及每个属性的类型值。某些Properties具有特殊的名称,尤其是WheCollectionollection。属性名称的约定如下:
- 对于列表项,Name 对应于索引。
- 对于字典,Name派生键值的字字符串版本。
- 对于集,Name基ON值的字字符串版本。
为了make区别更加显式,请将属性Name称括在方括号中。
-
在类中,添加以下方法:
ObjectVisitorprivate Static 字符串 GetPropertyName(IProperty 属性){ return property switch { // You can also treat `IListElementProperty`、`IDictionaryElementProperty` 和 `ISetElementProperty` 分开。 ICollectionElementProperty => $"[{property.Name}]", _ => property.Name };} -
更新方法以使用
VisitProperty检索给定类型的 Display Name。TypeUtility.GetTypeDisplayNameprotected 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;}控制台输出在如下所示:- 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 类型的较少信息
由于 不会重载 方法,因此列表值显示为 。要减少显示的信息量,请更新以使用 Utility 方法仅显示不包含子 Properties 的类型(例如图元、枚举和字符串)的值。
List<T>ToString()System.Collections.Generic.List1[UnityEngine.Color]VisitPropertyTypeTraits.IsContainer在 类中,更新 方法以使用确定该值是否为容器类型。如果是,则显示不带 值的类型 Name。否则,显示类型 Name 和 值:
ObjectVisitorVisitPropertyTypeTraits.IsContainerprotected 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;}
控制台输出在如下所示:
- 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} 五
PropertyVisitor.VisitCollectionPropertyVisitor.VisitListPropertyVisitor.VisitDictionaryPropertyVisitor.VisitSet
这些与 方法类似,但它们公开了各自 Collections 类型的 Generic Parameters。
VisitProperty添加指定的类型覆盖
将 与 一起使用。当为指定类型注册适配器时,如果在访问期间遇到目标类型,则会调用适配器而不是 方法。
PropertyVisitorIVisitPropertyAdapterVisitProperty在 类中,添加 和 的:
ObjectVisitorVector2ColorIVisitPropertyAdapterpublic 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}"); }}
开始访问子属性
当您运行 ON 数据访问者时,默认情况下,它会启动顶部关卡对象的访问。对于 Any 属性访问者,要开始访问对象的子 Properties,请向 方法通道。
PropertyContainer.AcceptPropertyPath-
更新方法以采取可选
DebugUtilities:PropertyPathpublic 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()); }} -
使用Object 调用
Data方法。控制台输出在如下所示:PrintObjectDump- 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} = 五个
完整的访客代码
访问者类的完整代码现在如下所示:
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}"); } }