克隆不同对象的属性的最佳方法 [英] Best way to clone properties of disparate objects
问题描述
我有一个MVC3应用程序,需要将视图模型与数据库模型同步。我发现自己编写了太多代码,无法在不同对象之间来回复制属性。我避开了可以只对数据模型进行子类化的这种情况,但是在其他时候,我发现它也太过局限了。
I have an MVC3 application that needs to sync view models with database models. I found myself writing way too much code to copy properties back and forth between the different objects. I avoided this where I could simply subclass the data model, but at other times, I found that too restricting.
我在Object上开发了一些扩展方法来支持浅层克隆具有相似名称的属性,并且效果很好。但是,我想知道是否有更有效的方法来完成同一件事。因此,我想这是在要求同行评审和改进此代码的选项。
I developed a few extension methods on Object to support shallow cloning of properties with similar names, and this has worked rather well. However, I'm wondering if there is a more efficient means to accomplish the same thing. So I guess this is asking for peer review and options to improve upon this code.
更新:
我发现更好地显式处理相关表。测试IsVirtual将防止在克隆过程中无意间影响关系。请参阅更新的CloneMatching方法。
UPDATE: I've found it better to handle related tables explicitly. Testing for IsVirtual will prevent relations from being inadvertently affected during cloning. See updated CloneMatching method. The others explicitly state which properties to update or exclude.
public static class CustomExtensions
{
public static T CloneMatching<T, S>(this T target, S source)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name,flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType) && !tPI.PropertyType.IsVirtual)
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
return target;
}
public static T CloneProperties<T, S>(this T target, S source, string[] propertyNames)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
if (propertyNames.Contains(sPI.Name))
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType))
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
}
return target;
}
public static T CloneExcept<T, S>(this T target, S source, string[] propertyNames)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
if (!propertyNames.Contains(sPI.Name))
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType))
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
}
return target;
}
}
以下是我如何使用它来绘制地图的示例数据模型的视图模型。
Here is an example of how I use it to map a view model to the data model.
DataSession.Quote.CloneProperties(viewModel,
new[] {"PaymentType","CardHolder","CardHolderZip","CardNumber","CardExp","CVC",
"AccountHolder","AccountHolderZip","ABA","Account",
"AccuracyAgreement","PrivacyTermsAgreement","ElectronicSignatureAgreement"});
推荐答案
您可以考虑使用 Object .MemberwiseClone
方法。
MemberwiseClone
方法创建通过创建新对象,然后将当前对象的非静态字段复制到新对象来进行浅表复制。 ( docs.microsoft )
The
MemberwiseClone
method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. (docs.microsoft)
该方法受保护。这意味着您必须在类中实现 Clone
方法。为了使事情更加有趣,您还可以在类中添加 ICloneable
。
The method is protected. It means that you have to implement the Clone
method in your classes. To make things even more fance you can add ICloneable
to your classes as well.
class MyClass: ICloneable
{
// all your code
MyClass Clone()
{
return (MyClass)this.MemberwiseClone();
}
}
这篇关于克隆不同对象的属性的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!