C # Initialize subclass based on parent

So basically I have it

public class Ticket{
    public TicketNumber {get; set;}
    ..a bunch more properties...
}

I want to add some properties using a subclass like this, using assumption instead of composition.

public class TicketViewModel(Ticket ticket){
    //set each property from value of Ticket passed in
    this.TicketNumber = ticket.TicketNumber;
    ...a bunch more lines of code..

    //additional VM properties
    public SelectList TicketTypes {get; private set;}
}

How to instantiate properties without having to write all lines like this

this.TicketNumber = ticket.TicketNumber;

Is there any shortcut? Something like a subclass constructor?

this = ticket; 

Obviously this does not work, but it is their way, so I do not need to change my subclass if the addng / remove property of the parent class? Or something?

+3
source share
4 answers

Take a look at Automapper

+5
source

, , :

public class Ticket{
    public string TicketNumber {get; set;}
    ..a bunch more properties...

    public Ticket (string ticketNumber, a bunch more values) {
         this.TicketNumber = ticketNumber;
         // a bunch more setters
    }
}

:

public class TicketViewModel : Ticket {
     public string SomeOtherProperty { get; set; }

     public TicketViewModel(string ticketNumber, ..., string someOtherProperty)
          : base(ticketNumber, ....) 
     {
          this.SomeOtherProperty = someOtherProperty;
     }
}
+2

, .

I often wanted it to be. I started programming with COBOL many years ago, and he had an operator MOVE CORRESPONDINGfor moving members of the same name from one record to another. I desired this in every language I have used since.

0
source

You can mark properties suitable for copying with an attribute and reflexively try to assign them. This is not the best way to do this.

0
source

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


All Articles