当前位置: 首页 > 编程语言 > C#

克隆不同对象属性的最佳方法分享

时间:2023-04-10 17:05:30 C#

克隆不同对象属性的最佳方法我有一个MVC3应用程序,需要将视图模型与数据库模型同步。我发现自己写了太多代码来在不同对象之间来回复制属性。我避免了这一点,我可以简单地将数据模型子类化,但有时我发现它限制太多。我已经在Object上开发了一些扩展方法来支持类似命名的属性的浅克隆,这工作得很好。但是,我想知道是否有更有效的方法来完成同样的事情。所以我猜它要求同行评审和改进此代码的选项。更新:我发现明确处理相关表会更好。测试IsVirtual可防止关系在克隆过程中受到无意中的影响。请参阅更新的CloneMatching方法。其他人则明确说明要更新或排除哪些属性。publicstaticclassCustomExtensions{publicstaticTCloneMatching(thisTtarget,Ssource)whereT:classwhereS:class{if(source==null){返回目标;}输入sourceType=typeof(S);输入targetType=typeof(T);BindingFlags标志=BindingFlags.IgnoreCase|BindingFlags.公共|BindingFlags.Instance;PropertyInfo[]属性=sourceType.GetProperties();foreach(PropertyInfosPIinproperties){PropertyInfotPI=targetType.GetProperty(sPI.Name,flags);如果(tPI!=null&&tPI.PropertyType.IsAssignableFrom(sPI.PropertyType)&&!tPI.PropertyType.IsVirtual){tPI.SetValue(target,sPI.GetValue(source,null),null);}}返回目标;}publicstaticTCloneProperties(thisTtarget,Ssource,string[]propertyNames)whereT:classwhereS:class{if(source==null){returntarget;}输入sourceType=typeof(S);输入targetType=typeof(T);BindingFlags标志=BindingFlags.IgnoreCase|BindingFlags.公共|宾迪ngFlags.Instance;PropertyInfo[]属性=sourceType.GetProperties();foreach(PropertyInfosPIinproperties){if(propertyNames.Contains(sPI.Name)){PropertyInfotPI=targetType.GetProperty(sPI.Name,flags);如果(tPI!=null&&tPI.PropertyType.IsAssignableFrom(sPI.PropertyType)){tPI.SetValue(target,sPI.GetValue(source,null),null);}}}返回目标;}publicstaticTCloneExcept(thisTtarget,Ssource,string[]propertyNames)whereT:classwhereS:class{if(source==null){returntarget;}输入sourceType=typeof(S);输入targetType=typeof(T);BindingFlags标志=BindingFlags.IgnoreCase|BindingFlags.公共|BindingFlags.Instance;PropertyInfo[]属性=sourceType.GetProperties();foreach(PropertyInfosPIinproperties){if(!propertyNames.Contains(sPI.Name)){PropertyInfotPI=targetType.GetProperty(sPI.Name,flags);如果(tPI!=null&&tPI.PropertyType.IsAssignableFrom(sPI.PropertyType)){tPI.SetValue(target,sPI.GetValue(source,null),null);}}}返回目标;下面是我如何使用它把视图模型映射到数据模型的例子上面是C#学习教程:Cloningdifferentobjects共享属性所有内容的最佳方式,如果对你和你有用需要了解更多C#学习教程,希望大家多多关注—DataSession.Quote.CloneProperties(viewModel,new[]{"PaymentType","CardHolder","CardHolderZip","CardNumber","CardExp","CVC","AccountHolder","AccountHolderZip","ABA","Account","AccuracyAgreement","PrivacyTermsAgreement","ElectronicSignatureAgreement"});本文来自网络收藏,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: