使用.Net Reflection 反射机制 动态获取对象字段内容的示例

来源:互联网 发布:寻侠武功突破数据八门 编辑:程序博客网 时间:2024/05/30 23:05

以下是对某个贴子的总结:   

class Program    {        static void Main(string[] args)        {            test t = new test();//创建实例             t.addtolist(1,"b");//集合中加如字段b            System.Console.WriteLine(" number = " + t.l.Count + "/nhave 1: " + t.l.ContainsKey(1));            System.Console.WriteLine(" value = " + t.l[1]);            System.Console.In.ReadLine();        }    }

    public class test     {         public byte a=33;         public Double b=22;         public int c;         public Dictionary <int, object> l = new Dictionary <int, object>();         public void addtolist(int ID,string FieldName)         {                         System.Reflection.FieldInfo field = this.GetType().GetField(FieldName);                        if (field == null)            {                //should do something                System.Console.WriteLine("Cannot get the field: {0}./n", FieldName);                System.Console.In.ReadLine();                return;            }

            System.Console.WriteLine("Name = " + field.Name + " type = " + field.FieldType);                        System.Console.WriteLine("value = " + field.GetValue(this) );

            l.Add(ID, field.GetValue(this));

                    }

    }

 

原创粉丝点击