日期:2014-05-17 浏览次数:20546 次
public class Employee { private string name; private int id; public string Name { get { return name; } set { name = value; } } public int ID { get { return id; } set { id = value; } } } protected void Test3() { Type myType = typeof(Employee); FieldInfo[] fi = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); foreach (var r in fi) { MemberTypes mymembertyps = r.MemberType; //我能找到这个r 对应的属性么? } PropertyInfo[] pi = myType.GetProperties(BindingFlags.Public | BindingFlags.Instance); }
public class Customer { private string name; public string Name { get { return name; } set { if(string.IsNullOrEmpty(name))throw new ArgumentException("Name cannot be blank","Name"); name = value; } } }
------解决方案--------------------
查找字段对应的后备属性?
这需要反射获得IL,然后反编译,再解析了。因为很多时候属性访问器是复杂的,看下面的代码:
class Person { public int ID { get; set; } private string firstName; private string lastName; public string Name { get { return firstName + " " + lastName; } set { firstName = (value + " ").Split(' ')[0]; lastName = (value + " ").Split(' ')[1]; } } public string Profile { get { DbContext db = new DbContext(); return db.Users.SingleOrDefault(x => x.ID == ID).Profile; } } public int RandomNumber { get { return new Random().Next(0, 100); } set { } } }