C# 根据父类对象初始化子类
所以基本上我有这个,
public class Ticket{
public TicketNumber {get; set;}
..a bunch more properties...
}
我想使用像这样的子类添加一些属性,使用包含而不是组合。
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;}
}
如何实例化属性而不必像这样编写所有行
this.TicketNumber = ticket.TicketNumber;
是否有某种快捷方式?类似于子类构造函数中的东西?
this = ticket;
显然这不起作用,但这是他们的某种方式,所以如果向父类添加/删除属性,我不必修改我的子类?或者什么?
So basically I have this
public class Ticket{
public TicketNumber {get; set;}
..a bunch more properties...
}
I want to add some properties using a subclass like this using subsumption 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 do I instantiate the properties without having to write all the lines like this
this.TicketNumber = ticket.TicketNumber;
Is there some kind of shortcut? Something like in the subclass constructor?
this = ticket;
Obviously this doesn't work but is their some way so I don't have to modify my subclass if addng/removing a property to the parent class? Or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看看 Automapper
Have a look at Automapper
您可以在基类上创建一个构造函数,然后从继承者中调用它,如下所示:
然后在继承类中只需执行以下操作:
You can create a constructor on your base class and then call that from the inheritor, like this:
Then in your inheriting class simply do:
抱歉,没有捷径。
我经常希望有。我很久以前就开始使用 COBOL 进行编程,它有一个
MOVE CORRESPONDING
语句,用于将同名成员从一条记录移动到另一条记录。从那时起我使用过的每一种语言都希望如此。Sorry, there's no shortcut.
I frequently wish there were. I started programming with COBOL ages ago, and it had a
MOVE CORRESPONDING
statement for moving the same-named members from one record to another. I've wished for that in every language I've used since then.您可以使用属性来标记可复制的属性,并反思性地尝试分配它们。这不是最好的方法。
You can mark the copy-able properties with an attribute and reflectively attempt to assign them. It's not the best way to go about it.