Use
public class BookChapter
{
public string book_id;
public string book_name;
public string chapter_num;
public string chapter_title;
public string chapter_Url;
public string chapter_content;
public BookChapter(BookChapter bc)
{
bc.CopyPublicFieldTo(this);
}
}
实现
/// <summary>
/// 反射实现类的对象之间相同属性值的复制, s => d
/// </summary>
/// <typeparam name="D"></typeparam>
/// <typeparam name="S"></typeparam>
/// <param name="s"></param>
/// <returns></returns>
public static void CopyPropertiesTo<D>(this object s, D d)
{
try
{
var Types = s.GetType();//获得类型
var Typed = d.GetType();
foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段
{
foreach (PropertyInfo dp in Typed.GetProperties())
{
if (dp.Name == sp.Name)//判断属性名是否相同
{
dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性
}
}
}
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 反射实现类的对象拷贝相同字段值的复制, s => d
/// </summary>
/// <typeparam name="D"></typeparam>
/// <param name="s">源头</param>
/// <param name="d">目标</param>
public static void CopyPublicFieldTo<D>(this object s,D d)
{
try
{
var Types = s.GetType();//获得类型
var Typed = d.GetType();
foreach (var sp in Types.GetFields(BindingFlags.Public | BindingFlags.Instance))//获得类型的属性字段
{
foreach (var dp in Typed.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
if (dp.Name == sp.Name)//判断名是否相同
{
dp.SetValue(d, sp.GetValue(s));//获得s对象属性的值复制给d对象的属性
}
}
}
}
catch (Exception e)
{
throw e;
}
}