Best Practices for mapping one object to another

前端 未结 4 890
后悔当初
后悔当初 2020-12-02 15:40

My question is, what is the best way I can map one object to another in the most maintainable manner. I cannot change the way the Dto object that we are getting is setup to

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 16:06

    This is a possible generic implementation using a bit of reflection (pseudo-code, don't have VS now):

    public class DtoMapper
    {
        Dictionary properties;
    
        public DtoMapper()
        {
            // Cache property infos
            var t = typeof(DtoType);
            properties = t.GetProperties().ToDictionary(p => p.Name, p => p);
         }
    
        public DtoType Map(Dto dto)
        {
            var instance = Activator.CreateInstance(typeOf(DtoType));
    
            foreach(var p in properties)
            {
                p.SetProperty(
                    instance, 
                    Convert.Type(
                        p.PropertyType, 
                        dto.Items[Array.IndexOf(dto.ItemsNames, p.Name)]);
    
                return instance;
            }
        }
    

    Usage:

    var mapper = new DtoMapper();
    var modelInstance = mapper.Map(dto);
    

    This will be slow when you create the mapper instance but much faster later.

提交回复
热议问题