2012-06-19 24 views
2

我對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; 
} 
+0

謝謝大家對你的答案。由於我不想在我的模型中使用邏輯代碼,因此Gabe的答案對我來說是最好的解決方案。但我牢記這些其他解決方案。 – android

回答

3

如何:

ActionTwoViewModel model = new ActionTwoViewModel(); 
model = createViewModel(model); 


private BaseViewModel createViewModel(BaseViewModel model) 
{ 
    // 
    // doing a lot of stuff here 
    // 

    return model; 
} 
+1

噢,我真的那麼容易。非常感謝你。 – android

1

使用base(MSDN上),你可以調用supercla ss構造函數,然後爲你的類添加你的東西。

public class ActionOneViewModel : BaseViewModel 
{ 
    public ActionOneViewModel (bool fooBar) : base() 
    { 
     //other stuff here 
     model.FooBar = fooBar; 
    } 
} 
+0

@RaphaëlAlthaus:哈哈哈,改變它:) – LaGrandMere

+0

請注意':base()'是默認值,超類構造函數將始終被調用。 – IngisKahn

3

你可以用一個做到這一點的方法或構造

,沒有必要有一個特殊的「createViewModel」的方法。

class BaseViewModel 
{ 
    public BaseViewModel() { 
    //stuff here 
    } 
    public string Name { get; set; } 
    public List<User> Users { get; set; } 
} 

class ActionOneViewModel : BaseViewModel 
{ 
    public ActionOneViewModel (bool fooBar) : base() { 
     FooBar = fooBar; 
    } 
    public bool FooBar { get; set; } 
} 

class ActionTwoViewModel : BaseViewModel 
{ 
    public ActionTwoViewModel(string pingPong) :base() { 
     PingPong = pingPong; 
    } 
    public string PingPong { get; set; } 
} 

使用

public ActionResult ActionTwo() 
{ 
    // this doesn't work (of course) 
    var model = new ActionTwoViewModel("blub"); 

    return View(model); 
} 
1

隨着一點點的通用性,這將工作:

private T CreateViewModel<T>() 
    where T : BaseViewModel, new() 
{ 
    BaseViewModel model = new T(); 
    //doing a lot of stuff here 
    return (T)model; 
} 

你可以用它喜歡:

ActionOneViewModel model1 = CreateViewModel<ActionOneViewModel>(); 
ActionTwoViewModel model2 = CreateViewModel<ActionTwoViewModel>();