读书人

反射有关问题:GetField方法获取私有字

发布时间: 2012-01-26 19:40:46 作者: rapoo

反射问题:GetField方法获取私有字段成员
class classMe
{ string str = "AAAA "}

static void Main(string[] args)
{
classMe me = new classMe() ;
FieldInfo fieldInfo = ty.GetFields( "str " ,BindingFlags.NonPublic|BindingFlags.GetField) ;
Console.WriteLine( fieldInfo.GetValue(me) );

}

但这里却无法得到str的值,那里有问题呢?

[解决办法]
兄弟,你的代码怎么这么多小毛病?没有冒号,变量错误等。下面这个例子可以跑:

using System;
using System.Text;
using System.Reflection;

namespace TestTest
{
class classMe
{ string str = "AAAA ";}

class Programs
{
static void Main(string[] args)
{
classMe me = new classMe();
Type t = me.GetType();

FieldInfo fieldInfo = t.GetField( "str ", BindingFlags.Instance | BindingFlags.GetField | BindingFlags.IgnoreCase | BindingFlags.NonPublic);
Console.WriteLine(fieldInfo.GetValue(me));

}
}
}

你的少了BindingFlags.Instance这个标记
[解决办法]
为了获取返回值,必须指定 BindingFlags.Instance 或 BindingFlags.Static。

指定 BindingFlags.Public 可在搜索中包含公共字段。

指定 BindingFlags.NonPublic 可在搜索中包含非公共字段(即私有字段和受保护的字段)。

指定 BindingFlags.FlattenHierarchy 以便沿层次结构向上包括 public 和 protected 静态成员;不包括继承类中的 private 静态成员。

读书人网 >C#

热点推荐