我正在寻找一种从基类的变量分配到派生类的基本部分的方法,而不必逐个显式地分配每个可分配属性。换句话说:从基类的变量开始,我想最终得到一个派生类的变量,该变量具有所有可分配的基本属性集,而不必记住它们是什么,或编辑代码,如果它们变化
我将视图模型创建为将要编辑的实体的基类的派生类。通常,这只是为了添加导航属性的ID,以便POST可以返回它们。例如:
public class ThingEditView : Thing
{
public int UsefulID { get; set; }
}
它被这样使用:
var foo = new ThingEditView
{
UsefulID = thisThing.Useful.ID,
A = thisThing.A,
B = thisThing.B,
/* and potentially many more properties from the base class Thing */
};
return View(foo);
但是,当我向基类Thing
添加属性而忘记编辑我初始化ThingEditView
或ThingDetailView
等所有位置时,我遇到了麻烦。我会喜欢能够说出
var foo = new ThingEditView
{
base = thisThing,
UsefulID = thisThing.Useful.ID
};
让编译器找出要分配的字段。有没有办法做到这一点?
感谢您的见解!
答案 0 :(得分:2)
void Main()
{
var thisThing= new ThingEditView {UsefulID = 1, A = 2, B = 3};
var foo = new ThingEditView(thisThing);
//foo.Dump();
}
// Define other methods and classes here
public class Thing
{
public int A {get; set;}
public int B {get; set;}
public Thing() {}
public Thing(Thing thing)
{
this.A = thing.A;
this.B = thing.B;
}
}
public class ThingEditView : Thing
{
public int UsefulID {get; set;}
public ThingEditView() {}
public ThingEditView(Thing thing) : base(thing) {
}
public ThingEditView(ThingEditView view) : base(view) {
this.UsefulID = view.UsefulID;
}
}
我会选择自动播放器。