我有一个类,里面有一些属性器,我在外面new了一个这个类的实例,给一些属性器赋了值,我现在想取得这些值,不用属性器的方式访问.
我要通过反射来取得这些属性器的值或者这些属性器对应的私有字段的值该怎么做呢?属性的名字我已经反射得到了,问题是值去不到各位大虾帮帮忙,谢谢

解决方案 »

  1.   

    先得到PropertyInfo fi
    再object temp = fi.GetValue(obj,null);
    temp 就是你要的
      

  2.   

    Type type = Type.GetType("ConsoleApplication1.Love");
    Object obj = type.InvokeMember("Love",
                    BindingFlags.DeclaredOnly |
                    BindingFlags.Public | BindingFlags.NonPublic |
                    BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
    //获取字段值 
    int f = (int)type.InvokeMember("field1", BindingFlags.GetField, null, obj, null);
      

  3.   

    //如果属性是private 的,需要设置Flag才能拿到
    foreach(PropertyInfo p in o.GetType().GetProperties(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance))  
    {  
            object obj   =   p.GetValue(o,null);  
            Console.WriteLine("{0}={1}",  p.Name, obj);  
    }
      

  4.   

    呵呵,我的文章讲的刚好就是你提的。
    我写了篇很简单的反射基本应用的文章以及反射在项目中实际使用的文章
    http://blog.csdn.net/go2newlife/archive/2007/11/27/1904687.aspx