C# Can't reflect into private field

2019-09-01 01:54发布

问题:

I got an issue.

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);

What am I doing wrong?

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...

回答1:

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;
}


回答2:

You have to ensure that your object is actually of the desired type and then call GetField on the right type object.

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var obj = new SerializableType();
        // reflection version of "obj is _SerializableType":
        if(typeof(_SerializableType).IsAssignableFrom(obj.GetType()))
        {
            var info = typeof(_SerializableType).GetField("name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            var name = info.GetValue(obj);
            Console.WriteLine(name);
        }

    }
}

public abstract class _SerializableType
{
    public string name = "xyz";
}

public class SerializableType : _SerializableType { }