using System;
using System.Reflection;
//要检查的类
public class Demo
{
// Make three fields:
// The first field is private.
private string m_field = "String A";//要检查类的成员属性
// The second field is public.
public string Field = "String B";
// The third field is public const (hence also literal and static),
// with a default value.
public const string FieldC = "String C";
}
//实施检查的类
public class Myfieldattributes
{
public static void Main()
{
Console.WriteLine("\nReflection.FieldAttributes");
//实例化检查类
Demo d = new Demo();
// Get a Type object for Demo, and a FieldInfo for each of
// the three fields. Use the FieldInfo to display field
// name, value for the Demo object in d, and attributes.
//
//获取要检查类的类对象mytype
Type myType = typeof(Demo);//注:typeof的参数直接是类名,不用""
//基于以上mytype,用方法getfield返回类型fieldinfo,
FieldInfo fiPrivate = myType.GetField("m_field",
BindingFlags.NonPublic | BindingFlags.Instance);//注意参数的bindingflags,要对应起来
//如下方法能数为object及fieldinfo类型
//d是要测试类的实例化对象
//此方法的参数为:要测试的实例化对象和要测试类的成员属性
DisplayField(d, fiPrivate);//调用方法displayfield显示上述加工的结果
FieldInfo fiPublic = myType.GetField("Field",
BindingFlags.Public | BindingFlags.Instance);
DisplayField(d, fiPublic);
FieldInfo fiConstant = myType.GetField("FieldC",
BindingFlags.Public | BindingFlags.Static);
DisplayField(d, fiConstant);
Console.ReadKey();
}
static void DisplayField(Object obj, FieldInfo f)
{
// Display the field name, value, and attributes.
//译上:显示属性名称,属性值,列
//{0},{1},{2}分别对应f.name,f.getvalue(obj),f.attributes
// \"为转义符表示",因为要输出"
// FieldAttributes是一个枚举类型,返回要检查类或对象的成员所有相关信息,比如是否private,public,literal,hashdefault等
Console.WriteLine("{0} = \"{1}\"; attributes: {2}",
f.Name, f.GetValue(obj), f.Attributes);//fieldinfo.getvalue(object)是:返回给定对象的属性的值
}
}
/* This code example produces the following output:
Reflection.FieldAttributes
m_field = "String A"; attributes: Private
Field = "String B"; attributes: Public
FieldC = "String C"; attributes: Public, Static, Literal, HasDefault
*/