使用泛型类型转换模型

时间:2013-12-05 19:35:07

标签: c# generics

您好我正在尝试使用泛型类型将一个对象转换为另一个对象,本质上我的模型具有相同的属性唯一不同的是命名空间

从下面可以看到

namespace Models.Entities
{
    public class News 
    {
        //Properties

        public String Title { get; set; }
        public String Teaser { get; set; }
        public String Body { get; set; }
        public String Old_Resource_Id { get; set; }
        public Image Image { get; set; }
        public List<City> Cities { get; set; }
        public Boolean ClientManaged { get; set; }
        public String Contributor { get; set; }
        public Category Category { get; set; }
        public DateTime? Publish { get; set; }
        public Boolean IsEdited { get; set; }
        public DateTime? Date_Edited { get; set; }
        public Boolean IsDeleted { get; set; }
    }
}

namespace Models.Import
{
    public class News 
    {
        //Properties

        public String Title { get; set; }
        public String Teaser { get; set; }
        public String Body { get; set; }
        public String Old_Resource_Id { get; set; }
        public Image Image { get; set; }
        public List<City> Cities { get; set; }
        public Boolean ClientManaged { get; set; }
        public String Contributor { get; set; }
        public Category Category { get; set; }
        public DateTime? Publish { get; set; }
        public Boolean IsEdited { get; set; }
        public DateTime? Date_Edited { get; set; }
        public Boolean IsDeleted { get; set; }
    }
}

我想从一个模型转换到另一个模型,但使用Generic Types

类似这样的事情

 private static List<T2> ConvertModel<T1, T2>(List<T1> items)
    {
        List<T2> convertedList = new List<T2>(); 

          foreach (var item in items)
          {
            convertedList.Add((T2)item);
          }

        return convertedList;
    } 

2 个答案:

答案 0 :(得分:7)

我建议您使用一些映射库,例如AutoMapper(可从NuGet获得):

Mapper.CreateMap<T1, T2>(); // create default mapping
var converted = Mapper.Map<List<T2>>(items); // map lists

默认映射将完成您的工作,因为您在源和目标类型中具有相同的属性:

Mapper.CreateMap<Models.Entities.News, Models.Import.News>();

答案 1 :(得分:2)

您可以修改类以支持它们之间的隐式转换:

namespace Models.Entities
{
    public class News
    {
    //your code

    public static implicit operator Models.Import.News(News value)
    {
        return new Import.News() 
        { 
            Title = value.Title,
            //and so on
        };
    }  
}

namespace Models.Import
{
    public class News
    {
        //your codes
        public static implicit operator Models.Entities.News(News value)
        {
            return new Entities.News() 
            {
                Title = value.Title,
                //and so on 
            };
        }
    }
 }