我有一個父類和很多兒童類:如何覆蓋方法返回類型?
public class ParentViewModel
{
public int Id{set;get;}
public string Name{set;get;}
<..and another 10 properties..>
}
public class ChildViewModel_1:ParentViewModel
{
public string Notes{set;get;}
}
現在我有創建一個子類一個方法:
public static ChildViewModel_1 MakeChild_1()
{
var child= new ChildViewModel_1
{
Id = ...
Name = ...
...And another parent properties...
Note = ...
}
return child;
}
他們有很多的simular代碼與父母的階級屬性。
我如何使方法來填充父類字段並使用它來創建子類?
我想:
public static ParentViewModel MakeParent()
{
var parent = new ParentViewModel
{
Id = ...
Name = ...
...And another properties...
}
return parent;
}
public static ChildViewModel_1 MakeChild_1()
{
var parent = MakeParent();
var child= parent as ChildViewModel_1;
child.Note = ...
return child;
}
但果然我獲得child = null
。
我讀this但看起來很困難。
任何建議?