C#无法反映到私有领域

问题描述:

我遇到了一个问题.

在Unity中,我想反映到一个私有字段中.但是我总是为fieldinfo获得null.我在做什么错了?

In Unity I want to reflect into a private field. But I always get null for the fieldinfo. what am I doing wrong?

public abstract class _SerializableType
{
    [SerializeField] private string name;
}

// because I am using a CustomPropertyDrawer for all inherited from _SerializeType
public class SerializableType<T> : _SerializableType { }
public class SerializableType : _SerializableType { }

[Serializable] public class CTech : SerializableType<_CouplingTechnology> { }

因此使用此方法应该可以正常工作.

so using this method should actually work.

        // type is CTech
        // propertyPath in that case is "name"
        FieldInfo info = type.GetField(propertyPath, BindingFlags.Instance
                         | BindingFlags.Public | BindingFlags.NonPublic);

我在做什么错了?

我在具有自己的CustomInspector的托管库中调用此方法.因此它反映到每个字段并确定如何显示它. AppDomain已完全信任.我不知道还有什么重要的...

I am calling this method in a managed library that has its own CustomInspector. so it reflects into every field and figure how to display it. AppDomain is fullyTrusted. I don't know what else could be of importance...

从派生类型中获取在基类中声明的私有字段的唯一方法是提升类层次结构.因此,例如,您可以执行以下操作:

The only way to get a private field that is declared in a base class from a derived type is to go up the class hierarchy. So for example, you could do something like this:

public FieldInfo GetPrivateFieldRecursive(Type type, string fieldName)
{
    FieldInfo field = null;

    do
    {
        field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public 
            | BindingFlags.NonPublic | BindingFlags.GetField);
        type = type.BaseType;

    } while(field == null && type != null);

    return field;
}