How can I get the value of a string property via Reflection?

前端 未结 9 1582
日久生厌
日久生厌 2020-11-30 04:46
public class Foo
{
   public string Bar {get; set;}
}

How do I get the value of Bar, a string property, via reflection? The following code will thr

9条回答
  •  無奈伤痛
    2020-11-30 05:18

    To get the property names of the object by just passing the object you can use this function may this works.

    just make object object a class and pass into it.

     public void getObjectNamesAndValue(object obj)
        {
            Type type = obj.GetType();
            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
            PropertyInfo[] prop = type.GetProperties(flags);
            foreach (var pro in prop)
            {
                System.Windows.Forms.MessageBox.Show("Name :" + pro.Name + " Value : "+  pro.GetValue(obj, null).ToString());
            }
    
        }
    

    But this will only work when the object properties are "Public"

提交回复
热议问题