我有两个对象,例如 A : B
我想在运行时将所有值从 A 复制到 B
代码
Cow cow = db.Cows.Find(id);
CowDetailViewModel model = new CowDetailViewModel(); // CowDetailViewModel : Cow
我想将值从牛变量复制到模型。CowDetailViewModel 中还有其他属性,我会在复制值后更改这些属性。
我有两个对象,例如 A : B
我想在运行时将所有值从 A 复制到 B
代码
Cow cow = db.Cows.Find(id);
CowDetailViewModel model = new CowDetailViewModel(); // CowDetailViewModel : Cow
我想将值从牛变量复制到模型。CowDetailViewModel 中还有其他属性,我会在复制值后更改这些属性。
CowDetailViewModel model = new CowDetailViewModel()
{
model.Property1 = cow.Property1,
model.Property2 = cow.Property2
////
////
};
您可以创建一个简单的扩展方法来复制所有公共属性
public static class CopyHelper
{
public static void CopyFrom(this object target, object source)
{
foreach (var pS in source.GetType().GetProperties())
{
foreach (var pT in target.GetType().GetProperties())
{
if (pT.Name != pS.Name) continue;
(pT.GetSetMethod()).Invoke(target, new[] {pS.GetGetMethod().Invoke(source, null)});
}
}
}
}