C# Can't reflect into private field

柔情痞子 提交于 2020-01-06 05:25:50

问题


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


来源:https://stackoverflow.com/questions/48008545/c-sharp-cant-reflect-into-private-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!