【问题标题】:Type.GetField on array field returns null数组字段上的 Type.GetField 返回 null
【发布时间】:2022-11-08 03:14:38
【问题描述】:

我正在尝试使用反射从类中获取一个数组字段。在一个简单的字段上它可以工作,在 Array 它没有。

这是课

public abstract class Condition : ScriptableObject
{
    public string Name;
    public virtual bool IsVerified() { return false; }
}

public class ExampleScript : MonoBehaviour
{
    [SerializeField] Condition _condition = null;
    [SerializeField] Condition[] _conditions = new Condition[0];
}

[CustomPropertyDrawer(typeof(Condition))]
public class ConditionPropertyDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        EditorGUI.BeginProperty(position, label, property);

        Type propertyType = GetPropertyType(property);

        EditorGUI.EndProperty();
    }

    private Type GetPropertyType(SerializedProperty property)
    {
        Type parentType = property.serializedObject.targetObject.GetType();
        Debug.Log($"{parentType} => {property.propertyPath}");
        FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
        Debug.Log(fi);
        return fi.FieldType;
    }
}

这是我得到字段的地方:

Type parentType = property.serializedObject.targetObject.GetType();
Debug.Log($"{parentType} => {property.propertyPath}");
FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Log(fi);

调试打印(条件变量):

ExampleScript => _condition
MyFullNameSpace.Condition _condition

调试打印(Condition[] var):

ExampleScript => _conditions.Array.data[0]
无效的

为什么它不返回正确的 FieldInfo?
提前致谢

【问题讨论】:

  • 您似乎正在尝试获取一个名为 "_conditions.Array.data[0]" 的字段。你没有这样的领域。 (我们没有关于您从哪里获得 property.propertyPath 的背景信息,这使得我们很难提供进一步的帮助。)
  • (如果您可以提供minimal reproducible example,通常会更容易为您提供帮助。从您所展示的内容来看,确实看起来像这样与尝试使用不是字段名称的值有关。如果现实更复杂 - 好吧,这就是一个最小的例子有助于澄清事情的地方。)
  • @JonSkeet 已更新
  • SerializedProperty.propertyPath 是与SerializedObject 相关的路径,它不是字段的路径。

标签: c# unity3d reflection


【解决方案1】:

GetField(property.propertyPath, ...) 不起作用,因为它不走路径。它只需要属性名称。您可以通过在点处拆分 pathString 来获得路径末尾的属性 - 在基础中找到第一个对象 - 然后在第一个对象中找到第二个对象......

请记住,如果集合即将到来,路径会使用关键字 Array “警告”您。你的路径有类似 class1.class2.Array.data[i].class3 所以不要在类 2 中搜索名为“Array”的属性。而是将对象强制转换为 IEnumerable 并获取 i 项。

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多