指引网

当前位置: 主页 > 编程开发 > .NET >

使用.Net Reflection 获取对象字段内容

来源:网络 作者:佚名 点击: 时间:2017-11-17 03:44
[摘要] 以下是对某个贴子的总结: class Program { static void Main(string[] args) { test t = new test();//创建实例 t.addtolist(1,"b");//集合中加如字段b System.Console.WriteLine(" number = " + t.l.Count + "\nha

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

         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));
            }
        }

 

------分隔线----------------------------