I have the class Order1 and an instance of the class Order2, both classes have the same field, I need to convert an instance from Order2 to Order1, how to do it? All fields are public.

  • What is the class inheritance scheme? - Valera Kvip
  • 6
    Why did it take different classes? Public fields? Actually you have 2 options: manually write a method and explicitly prescribe which field is copied to; either through the reflection in the cycle, go through the fields and find the corresponding ones. Well, there are ready-made mappers for this purpose in nuget (which work according to the second principle), for example, Automapper. - Andrei NOP
  • 3
    Why do you need it? If you need this, it is quite possible that your data structure is incorrectly organized. - VladD
  • four
    We need to take the fields of one object and assign them to another - Grundy

2 answers 2

I implemented it

class Order1 { public int OrderNum; public object Seller; public object[] goods; public Order1(int goodsQuantity, int OrderNum) { goods = new object[goodsQuantity]; Seller = "Petya"; this.OrderNum = OrderNum; } public static explicit operator Order1(Order2 v) { return new Order1(v.goods.Length, v.OrderNum) { OrderNum = v.OrderNum, Seller = v.Seller, goods = v.goods }; } } class Order2 { public int OrderNum; public object Seller; public object[] goods; public Order2(int goodsQuantity, int OrderNum) { goods = new object[goodsQuantity]; Seller = "Vasya"; this.OrderNum = OrderNum; } class Program { static void Main(string[] args) { Order1 or1 = new Order1(15, 45); Order2 or2 = new Order2(12, 47); or1 = (Order1)or2; } } 
  • four
    Horror. Why such a perversion? Can't you just make 2 different instances of the same class? I can't even figure out where your decision might be needed ... - guitarhero

You have incorrectly organized data, inheritance. Well, if you want to be perverted, then:

 public void Convert(object from, object to) { Type tFrom = from.GetType(); Type tTo = to.GetType(); PropertyInfo[] pFrom = tFrom.GetProperties(); foreach (PropertyInfo property in pFrom) { PropertyInfo propertyTo = tTo.GetProperty(property.Name); if (property.CanRead && propertyTo.CanWrite && property.PropertyType.Equals(propertyTo.PropertyType)) propertyTo.SetValue(to, property.GetValue(from)); } }