namespace ClassLibrary4
{
public class Users
{
public string UserName { get; set; }
public int Age { get; set; }
} class MyClass
{
Users u = new Users() { UserName="", Age=23 };
}
}
Users u = new Users() { UserName="", Age=23 };这里的UserName,,Age都是自己手动敲上去的,有时一个实体会有几十个字段,这样太麻烦,有没有什么快速的方法,直接让他全出来,最好是出来字段名后面跟上这个字段类型的默认值,或者
字段名 = item.字段名,这样的格式此功能在转换实体时很有用,比如:
foreach (var item in User2List)
{
Users u = new Users() { UserName=item.姓名, Age=item.年龄 };
}
java的BeanUtils里都有 copyProperties(Object dest, Object orig)
除非有大量的实体要相互拷贝,一般情况下反射也无妨。
/// <summary>
/// 提供两个对象的属性复制的方法。
/// 注意:不支持List属性复制。
/// </summary>
/// <param name="fromObj"></param>
/// <param name="toObj"></param>
public static void CopyProperty(object fromObj, object toObj)
{
Type fromType = fromObj.GetType();
Type toType = toObj.GetType(); PropertyInfo[] fromPis = fromType.GetProperties();
PropertyInfo[] toPis = toType.GetProperties(); foreach (PropertyInfo pi in fromPis)
{
PropertyInfo toProperty = toType.GetProperty(pi.Name);
if (toProperty != null)
{
toProperty.SetValue(toObj, pi.GetValue(fromObj, null), null);
}
}
}