C#通过反射获取类字段
1 class RefSkill 2 { 3 int Id; 4 string Name; 5 string Desc; 6 7 public RefSkill(int id, string name, string desc) 8 { 9 Id = id; 10 Name = name; 11 Desc = desc; 12 } 13 14 public object GetValue(string enumTytpe) 15 { 16 object obj = null; 17 18 try 19 { 20 FieldInfo info = GetType().GetField(enumTytpe, BindingFlags.Instance | BindingFlags.NonPublic); 21 if (null != info) 22 { 23 obj = info.GetValue(this); 24 } 25 } 26 catch (Exception ex) 27 { 28 Console.WriteLine(ex.ToString()); 29 } 30 31 return obj; 32 } 33 }
定义枚举,枚举名字对应的是类中字段的名字:
1 public enum ERefSkill 2 { 3 Id, 4 Name, 5 Desc, 6 }
测试:
1 static void Main() 2 { 3 RefSkill refSkill = new RefSkill(12, "控制", "可以控制敌人1秒不动"); 4 int id = (int)refSkill.GetValue((ERefSkill.Id).ToString()); 5 Console.WriteLine(id); 6 Console.ReadKey(); 7 }