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

将一个对象映射到另一个对象的最佳实践分享

时间:2023-04-11 11:21:29 C#

C#学习教程:将一个对象映射到另一个对象的最佳实践对象的最佳方法是什么。我无法更改我们获取的Dto对象被设置为更加规范化的方式,因此我需要创建一种方法将其映射到我们的对象的实现。以下示例代码显示了我需要发生的事情:classProgram{staticvoidMain(string[]args){vardto=newDto();dto.Items=newobject[]{1.00m,true,"三"};dto.ItemsNames=new[]{“一”,“二”,“三”};varmodel=GetModel(dto);Console.WriteLine("一:{0}",model.One);Console.WriteLine("二:{0}",model.Two);Console.WriteLine("三:{0}",model.Three);控制台.ReadLine();}privatestaticModelGetModel(Dtodto){varresult=newModel();结果.One=Convert.ToDecimal(dto.Items[Array.IndexOf(dto.ItemsNames,"One")]);result.Two=Convert.ToBoolean(dto.Items[Array.IndexOf(dto.ItemsNames,"Two")]);result.Three=dto.Items[Array.IndexOf(dto.ItemsNames,"三")].ToString();返回结果;}}classDto{publicobject[]Items{get;放;}publicstring[]ItemsNames{get;放;}}classModel{publicdecimalOne{get;放;}publicboolTwo{get;放;}publicstring三{get;放;我想如果我有某种接受模型对象propertyInfo的映射器类,我想转换成的类型,以及“项目name”,那该有多好。有没有人有任何建议让这个更干净?谢谢!我会选择AutoMapper,这是一个开源和免费的映射库,它允许根据约定将一种类型映射到另一种类型(即映射相同名称和相同/派生/可转换类型的公共属性,以及许多其他智能类型)。非常易于使用,可以让你实现这样的目标:Modelmodel=Mapper.Map(dto);不确定你的确切要求,但AutoMapper还支持自定义值解析器,它可以帮助您编写特定映射器的单个泛型实现。这是一个可能的泛型实现,使用一点反射(伪代码,现在没有VS):publicclassDtoMapper{Dictionaryproperties;publicDtoMapper(){//缓存属性信息vart=typeof(DtoType);properties=t.GetProperties().ToDictionary(p=>p.Name,p=>p);}publicDtoTypeMap(Dtodto){varinstance=Activator.CreateInstance(typeOf(DtoType));foreach(varpinproperties){p.SetProperty(instance,Convert.Type(p.PropertyType,dto.Items[Array.IndexOf(dto.ItemsNames,p.Name)]);返回实例;}}用法:varmapper=newDtoMapper();varmodelInstance=mapper.Map(dto);这在创建映射器实例时会很慢,但稍后会快得多。以上就是C#学习教程的全部内容:一个对象映射到另一个对象的最佳实践。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注——//////mapproperties/////////privatevoidMapProp(objectsourceObj,objecttargetObj){类型T1=sourceObj.GetType();类型T2=targetObj.GetType();PropertyInfo[]sourceProprties=T1.GetProperties(BindingFlags.Instance|BindingFlags.Public);PropertyInfo[]targetProprties=T2.GetProperties(BindingFlags.Instance|BindingFlags.Public);foreach(varsourcePropinsourceProprties){objectosourceVal=sourceProp.GetValue(sourceObj,null);intentIndex=Array.IndexOf(targetProprties,sourceProp);如果(entIndex>=0){vartargetProp=targetProprties[entIndex];targetProp.SetValue(targetObj,osourceVal);}}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢