创建 UserManager 实例的语法是什么?

What is the syntax for creating an instance of UserManager actually doing?

VS2013、MVC5、VB

有人帮助我解决了在 的 MVC5 应用程序的种子方法中创建用户的问题。

这道题是想问这行正常运行的代码是怎么回事:

Dim myUserManager = New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(New ApplicationDbContext))

下面对我不明白的地方进行解释。我会把这个分解成我理解的,然后是我不理解的。

New UserManager(Of ApplicationUser)... is creating an instance of UserManager, yes?

之后还有2个'new things'

... (New UserStore(Of ApplicationUser)(New ApplicationDbContext))

我不明白那个语法。在新的 UserStore 中有一个完整的括号,后跟用于新上下文的另一组括号。

那是我不理解的部分。我不理解的一部分是 (1) 这种语法的一般含义,另一部分是 (2) 为什么在这种情况下需要这种语法。

"New UserStore" 是什么意思,后面的 "New" 是什么意思?

有没有更长的方式来写这个更能说明问题?

下面一行代码:

Dim myUserManager = New UserManager(Of ApplicationUser)(New UserStore(Of ApplicationUser)(New ApplicationDbContext))

相当于:

Dim myApplicationDbContext As New ApplicationDbContext
Dim myUserStore As New UserStore(Of ApplicationUser)(myApplicationDbContext)
Dim myUserManager = New UserManager(Of ApplicationUser)(myUserStore)
  1. 第一步是创建一个新的 ApplicationDbContext 对象,它的 constructor 没有参数。
  2. 第二步是创建一个新的 UserStore(Of ApplicationUser) 对象,它将已经创建的 ApplicationDbContext 对象作为其构造函数的参数。
  3. 第三步是创建一个新的 UserManager(Of ApplicationUser) 对象,它将已经创建的 UserStore(Of ApplicationUser) 对象作为其构造函数的参数。

类型名称的 (Of ...) 部分是泛型参数。 .NET 支持 generic typesOf 之后的部分是泛型 class 的类型参数。因此,正如 Dim x As New List(Of String) 创建字符串列表一样,UserStore(Of ApplicationUser) 创建用于存储应用程序用户的用户存储。

您似乎不理解语句中使用的泛型类型参数 (this may help)。不确定这是否有帮助,但您可以这样分解:

' Create an instance of ApplicationDbContext.
' The parens were missing in the original.
Dim context = New ApplicationDbContext()
' Create an instance of the generic type UserStore(Of T), with
' ApplicationUser as the type parameter, T.
' The type of userStore is therefore UserStore(Of ApplicationUser).
' context is passed as a parameter to the constructor.
Dim userStore = New UserStore(Of ApplicationUser)(context)
' Create an instance of the generic type UserManager(Of T), with
' ApplicationUser as the type parameter, T.
' The type of myUserManager is therefore UserManager(Of ApplicationUser).
' userStore is passed to the constructor as a parameter
Dim myUserManager = New UserManager(Of ApplicationUser)(userStore)