原文:http://bbs.csdn.net/topics/320248154
问题:
public class A { public int Pro1 { get; set; } public int Pro2 { get; set; } } A a = new A();
如何获取a.Pro1的字符串名称。即如何获得"Pro1"
方案一:
using System.Reflection; Type t = typeof(A); foreach(PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BidngFlags.Public)) { Console.WriteLine(pi.Name); }
方案二:反射,
System.Reflection.PropertyInfo[] propertys =对像.GetType().GetProperties(); foreach (System.Reflection.PropertyInfo info in propertys) { //info.Name 属性名称 }
void Test() { A a = new A(); Type t = a.GetType(); foreach(PropertyInfo info in t.GetProperties()) { Console.WriteLine(info.Name); } Console.ReadLine(); }
方案三:(可以反过来使用得到这个属性的值吗?)
a.GetType().GetProperty("Pro1").GetValue(a).ToString()
方案四:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication15 { public partial class Form1 : Form { public Form1() { InitializeComponent(); A AA = new A(); AA.Pro1 = 1; AA.Pro2 = 2; B BB = new B(); BB.Pro1 = 1; BB.Pro2 = 2; MessageBox.Show(((DefaultValueAttribute)(AA.GetType().GetProperty(AA.GetNeededPropName) .GetCustomAttributes(typeof(DefaultValueAttribute), false)[0])).Value.ToString()); //1 MessageBox.Show(((DefaultValueAttribute)(BB.GetType().GetProperty(BB.GetNeededPropName) .GetCustomAttributes(typeof(DefaultValueAttribute), false)[0])).Value.ToString()); //4 } class X { virtual public String GetNeededPropName { get; set; } } class A : X { [DefaultValue(1)] public int Pro1 { get; set; } [DefaultValue(2)] public int Pro2 { get; set; } public override string GetNeededPropName { get { return "Pro1"; } } } class B : X { [DefaultValue(3)] public int Pro1 { get; set; } [DefaultValue(4)] public int Pro2 { get; set; } public override string GetNeededPropName { get { return "Pro2"; } } } } }