using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; namespace DataTransferService.Method { public abstract class EntityBase { /// /// 索引器,可以用字符串访问变量属性 /// /// 属性名称 /// 属性值,如果传入的属性名称不存在,返回null public object this[string propertyName] { get { //从所有获取的属性值中找到传入的属性值 var pi = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).FirstOrDefault(p => p.Name.ToUpper().Equals(propertyName.ToUpper())); if (null != pi && null != pi.GetMethod) { return pi.GetValue(this); } else { return null; } } set { var pi = this.GetType().GetProperties().FirstOrDefault(p => p.Name.ToUpper().Equals(propertyName.ToUpper())); if (null != pi && null != pi.SetMethod) { if (pi.PropertyType.Equals(value.GetType())) { pi.SetValue(this, value); } else { pi.SetValue(this, Convert.ChangeType(value, pi.PropertyType)); } } } } } }