C# 在C中将基类转换为子类#
我对面向对象编程和C#还是个新手,我正在努力理解,如何尽可能干净利落地编写代码。在我的ASP.NET MVC 3应用程序中,我在一个控制器中有多个操作(本例代码中有两个),这些操作都返回不同的C# 在C中将基类转换为子类#,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,我对面向对象编程和C#还是个新手,我正在努力理解,如何尽可能干净利落地编写代码。在我的ASP.NET MVC 3应用程序中,我在一个控制器中有多个操作(本例代码中有两个),这些操作都返回不同的ViewModel,它们都继承相同的BaseViewModel。这是因为我需要每个动作都有相同的数据,但每个动作都有额外的属性 我知道我可以简单地为ActionOneViewModel创建一个构造函数,它接收一个ViewModel对象。但这是常见的方法吗?或者有其他选择吗 查看模型: class BaseV
ViewModel
,它们都继承相同的BaseViewModel
。这是因为我需要每个动作都有相同的数据,但每个动作都有额外的属性
我知道我可以简单地为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;
}
那么:
ActionTwoViewModel model = new ActionTwoViewModel();
model = createViewModel(model);
private BaseViewModel createViewModel(BaseViewModel model)
{
//
// doing a lot of stuff here
//
return model;
}
使用(在MSDN上),您可以调用超类构造函数,然后为类添加内容
public class ActionOneViewModel : BaseViewModel
{
public ActionOneViewModel (bool fooBar) : base()
{
//other stuff here
model.FooBar = fooBar;
}
}
您可以在方法或构造函数中执行此操作 使用该方法,不需要特殊的“createViewModel”方法
有了一点通用性,这将起作用:
private T CreateViewModel<T>()
where T : BaseViewModel, new()
{
BaseViewModel model = new T();
//doing a lot of stuff here
return (T)model;
}
private T CreateViewModel()
其中T:BaseViewModel,new()
{
BaseViewModel模型=新的T();
//在这里做很多事情
回归(T)模型;
}
您可以像这样使用它:
ActionOneViewModel model1 = CreateViewModel<ActionOneViewModel>();
ActionTwoViewModel model2 = CreateViewModel<ActionTwoViewModel>();
actionOneViewModel1=CreateViewModel();
ActionTwoViewModel2=CreateViewModel();
@RaphaëlAlthaus:hahaha,更改:)注意,:base()
是默认值,超级类构造函数将始终被调用。哦,天哪,这真的很简单。非常感谢,谢谢大家的回答。因为我不想在我的模型中有任何逻辑代码,Gabe的答案对我来说是最好的解决方案。但我会记住其他的解决方案。
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>();