public class AttributeInstance
{
public void T TestAttr()
{
LSize lSize = new LSize
{
height = "234",
width = "678"
};
//根据USize属性Height,Width对应的特性名称获取LSize的属性值,赋值给USize属性
USize uSize = lSize.ToCustomEntity<USize>();
//打印出结果
System.Diagnostics.Debug.WriteLine(uSize.Width);
System.Diagnostics.Debug.WriteLine(uSize.Height);
}
}
public class USize
{
[ColumnName("width")]
public string Width { get; set; }
[ColumnName("height")]
public string Height { get; set; }
}
public class LSize
{
public string width { get; set; }
public string height { get; set; }
}
}
//obejct扩展方法
public static class ObjectHelper
{
//object扩展方法,更具对象的属性的特性名称,读取对象的属性值,并赋值
public static T ToCustomEntity<T>(this object entity){
T t = Activator.CreateInstance<T>();
if (entity == null)
return t;
string columnName = "";
foreach (PropertyInfo p in typeof(T).GetProperties())
{
object[] baseAttributes = p.GetCustomAttributes(typeof(BaseAttribute), false);
if (baseAttributes != null && baseAttributes.Length > 0)
{
columnName = ((BaseAttribute)baseAttributes[0]).Name;
p.SetValue(t, entity.GetPropertyValue(columnName), null);
}
}
return t;
}
public static object GetPropertyValue(this object entity, String property)
{
Type info = entity.GetType();
var props = info.GetProperty(property);
object value = props.GetValue(entity, null);
return value;
}
}