我對OOP和C#真的很陌生,我試圖理解,我可以如何儘可能地寫我的代碼。在我的ASP.NET MVC 3應用程序中,我有一個控制器中的多個動作(這個示例代碼中有兩個),它們都返回一個不同的ViewModel
,它們都繼承了相同的BaseViewModel
。這是因爲我需要每個動作都有相同的數據,但每個動作都有其他屬性。將基類轉換爲C#中的子類#
我知道我可以簡單地爲ActionOneViewModel
創建一個構造函數,它接收ViewModel
對象。但這是做這件事的常見方式嗎?還是有其他選擇嗎?
視圖模型:
class BaseViewModel
{
public string Name { get; set; }
public List<User> Users { get; set; }
}
class ActionOneViewModel : BaseViewModel
{
public bool FooBar { get; set; }
}
class ActionTwoViewModel : BaseViewModel
{
public string PingPong { get; set; }
}
控制器操作:
public ActionResult ActionOne()
{
// this doesn't work (of course)
ActionOneViewModel model = (ActionOneViewModel)createViewModel();
model.FooBar = true;
return View(model);
}
public ActionResult ActionTwo()
{
// this doesn't work (of course)
ActionTwoViewModel model = (ActionTwoViewModel)createViewModel();
model.PingPong = "blub";
return View(model);
}
private BaseViewModel createViewModel()
{
BaseViewModel model = new BaseViewModel();
//
// doing a lot of stuff here
//
return model;
}
謝謝大家對你的答案。由於我不想在我的模型中使用邏輯代碼,因此Gabe的答案對我來說是最好的解決方案。但我牢記這些其他解決方案。 – android