C # Inheritance and Inheritance Inheritance Hierarchy

I would like to create a new object of type B from an existing object of type A. B inherits from A. I would like to make sure that all property values ​​in the object of type A are copied to the object of type B. What is the best method to achieve this?

class A { public int Foo{get; set;} public int Bar{get; set;} } class B : A { public int Hello{get; set;} } class MyApp{ public A getA(){ return new A(){ Foo = 1, Bar = 3 }; } public B getB(){ A myA = getA(); B myB = myA as B; //invalid, but this would be a very easy way to copy over the property values! myB.Hello = 5; return myB; } public B getBAlternative(){ A myA = getA(); B myB = new B(); //copy over myA property values to myB //is there a better way of doing the below, as it could get very tiresome for large numbers of properties myB.Foo = myA.Foo; myB.Bar = myA.Bar; myB.Hello = 5; return myB; } } 
+4
source share
3 answers
 class A { public int Foo { get; set; } public int Bar { get; set; } public A() { } public A(A a) { Foo = a.Foo; Bar = a.Bar; } } class B : A { public int Hello { get; set; } public B() : base() { } public B(A a) : base(a) { } } 

EDIT

If you do not want to copy each property, you can serialize A and B and serialize your instance of A (let's say Stream, not a file) and initialize your instance of B with it. But I warn you, this is disgusting and has quite a bit of overhead:

 A a = new A() { Bar = 1, Foo = 3 }; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(A)); System.IO.Stream s = new System.IO.MemoryStream(); xs.Serialize(s, a); string serial = System.Text.ASCIIEncoding.ASCII.GetString(ReadToEnd(s)); serial = serial.Replace("<A xmlns", "<B xmlns"); serial = serial.Replace("</A>", "</B>"); s.SetLength(0); byte[] bytes = System.Text.ASCIIEncoding.ASCII.GetBytes(serial); s.Write(bytes, 0, bytes.Length); s.Position = 0; xs = new System.Xml.Serialization.XmlSerializer(typeof(B)); B b = xs.Deserialize(s) as B; 

You can get more information about ReadToEnd here .

+4
source

You can define an explicit casting operator for B:

  public static explicit operator B(A a) { B b = new B(); b.Foo = a.Foo; b.Bar = a.Bar; b.Hello = 5; return b; } 

so you can:

 B myB = (B)myA; 
+3
source

This is not possible in the OO engine, but AutoMapper was created for this very use.

0
source

Source: https://habr.com/ru/post/1337299/


All Articles