我经常以这样的写作课结束:
public class Animal
{
public string Colour { get; set; }
public int Weight { get; set; }
public Animal(Dog data)
{
this.Colour = data.Colour;
this.Weight = data.Weight;
}
public Animal(Cat data)
{
this.Colour = data.Colour;
this.Weight = data.Weight;
}
}当你有很多属性和类型时,你很快就会得到大量的锅炉板代码。在这种情况下,理想情况下,我只需创建一个IAnimal接口并引用它。我目前的情况是狗和猫类存在于第三方程序集中,而我无法修改它们。我唯一能想到的解决办法是:
public class Animal
{
public string Colour { get; set; }
public int Weight { get; set; }
public Animal(Cat data){Init(data);}
public Animal(Dog data){Init(data);}
private void Init(dynamic data)
{
this.Colour = data.Colour;
this.Weight = data.Weight;
}
}这是可行的,但我失去了所有类型的安全性,有比构造函数注入更好的解决方案吗?
谢谢,
乔
编辑:这里是一个真实世界的例子。我有一个第三方库,它返回3个对象,名为:
(这些都是从服务引用中自动生成的类,并且属性几乎是相同的)
我不处理这三个对象,而是处理单个PageData对象或它们的集合。
发布于 2015-08-20 12:50:01
您可以在一个公共构造函数中获得所有其他构造函数调用的逻辑:
public class Animal
{
public string Colour { get; set; }
public int Weight { get; set; }
public Animal(Dog data) : this (data.Colour, data.Weight)
{
}
public Animal(Cat data) : this (data.Colour, data.Weight)
{
}
private Animal(string colour, int weight)
{
this.Colour = colour;
this.Weight = weight;
}
}这与您的第二个解决方案非常相似,但它不会失去类型安全性。
发布于 2015-08-20 12:56:03
目前,
Dog和Cat类存在于第三方程序集中,无法对它们进行修改
我建议基于Automapper的解决方案:
public static class AnimalFactory
{
public static Animal Create<T>(T source)
where T : class
{
Mapper.CreateMap<T, Animal>();
return Mapper.Map<Animal>(source);
}
}用法:
var catAnimal = AnimalFactory.Create(cat);
var dogAnimal = AnimalFactory.Create(dog);当然,如果需要,您可以提供一种自定义映射配置的方法。
发布于 2015-08-20 12:46:09
如果您不想像这样乱扔类,可以尝试扩展方法吗?
public static Animal ToAnimal(this Dog item)
{
return new Animal() {Weight = item.Weight, Colour = item.Colour};
}
public static Animal ToAnimal(this Cat item)
{
return new Animal() {Weight = item.Weight, Colour = item.Colour};
}https://stackoverflow.com/questions/32118575
复制相似问题