【发布时间】:2020-07-08 14:58:54
【问题描述】:
我现在正在放屁。我正在尝试为我的所有控制器设置一个 BaseController。有了这个,我想要一种方法来为所有从 BaseViewModel 继承的 View 创建各种 ViewModel,并设置 BaseViewModel 中的属性。 BaseViewModel 中的属性是根据所使用的控制器操作设置的,因此我不能只在 BaseViewModel 构造函数中设置它们。
但是,当我调用它时,我不断返回 Null 值。
这是BaseController中的方法:
/// <summary>
/// Instantiate a ViewModel
/// </summary>
/// <typeparam name="T">ViewModel that inherits <see cref="BaseViewModel"/></typeparam>
/// <returns></returns>
public T SetupViewModel<T>(int? currentTrack = null) where T : BaseViewModel
{
// Return a new instance of a ViewModel
return new BaseViewModel(_Context)
{
// Set the current track
CurrentTrack = currentTrack,
} as T;
}
我在公共类 HomeController 中这样称呼它:BaseController:
/// <summary>
/// Main page
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
// Instantiate the view model
var vm = SetupViewModel<HomeViewModel>();
// Setup the repositories
vm.SetupRepositories();
// Load the tables base on the user
vm.Load(GetLoggedInUserName());
// Return the view with model
return View(vm);
}
当我在 vm.SetupRepositories() 处中断时,变量 vm 为 NULL。
EDIT(回复 cmets 关于 new() 当我尝试 new() 时,我得到了这个
【问题讨论】:
-
您的 HomeViewModel 是否继承自 BaseViewModel?
-
您正在创建 BaseViewModel 的对象而不是 T 的对象。您不能将 BaseViewModel 对象转换为 T 对象,这就是您将其设为 null 的原因。
-
SetupViewModel()方法正在创建一个BaseViewModel实例,但在return上它会将其称为T,在本例中为HomeViewModel。由于转换失败,它返回null。我希望您的方法是调用new T()并通过添加另一个通用约束来启用它:where T : BaseViewModel, new() -
@Nenad 是的; Chentan,我试过 return new T(_Context) 但这没有编译。我认为它会因为我说 T 必须继承 BaseViewModel ,它的构造函数中有它。
-
@Red_Phoenix,您不能将参数传递给构造函数。
new()约束的含义是:“该类型有一个 parameter-less 构造函数”。尝试将_Context作为属性传递
标签: c# generics asp.net-core-mvc asp.net-mvc-viewmodel