C#无法反映到私有领域 [英] C# Can't reflect into private field

查看:117
本文介绍了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;
}

这篇关于C#无法反映到私有领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆