Find a private field with Reflection?

Given this class

class Foo
{
    // Want to find _bar with reflection
    [SomeAttribute]
    private string _bar;

    public string BigBar
    {
        get { return this._bar; }
    }
}

I want to find the private item _bar that I will mark with a attribute. Is that possible?

I have done this with properties where I have looked for an attribute, but never a private member field.

What are the binding flags that I need to set to get the private fields?


使用BindingFlags.NonPublicBindingFlags.Instance标志

FieldInfo[] fields = myType.GetFields(
                         BindingFlags.NonPublic | 
                         BindingFlags.Instance);

你可以像做一个物业一​​样做:

FieldInfo fi = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance);
if (fi.GetCustomAttributes(typeof(SomeAttribute)) != null)
    ...

Get private variable's value using Reflection:

var _barVariable = typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(objectForFooClass);

Set value for private variable using Reflection:

typeof(Foo).GetField("_bar", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(objectForFoocClass, "newValue");

Where objectForFooClass is a non null instance for the class type Foo.

链接地址: http://www.djcxy.com/p/21204.html

上一篇: 使用C#中的反射从字符串获取属性值

下一篇: 用Reflection找到一个私人领域?