New Form() With {} 语法错误 vb.net

syntax error in New Form() With {} vb.net

Dim name As String = "hello"
If CType(My.Application.OpenForms(name), Faker) Is Nothing Then
    New Faker() With {.Name = name, .Title = String.Format("{0} - ID:{1}", "hello", Me.ClassClient.ClientAddressID)}.Show()
End If

New 中的语法错误,如果我删除所有代码并使用 {} 和 F.show() 编写 Dim F As New Faker() 没有错误但不起作用并在 运行 时给我错误程序对象引用未设置为对象实例

这里有人能帮我吗

这里有两个答案 Constructing an object and calling a method without assignment in VB.Net 应该有所帮助。

  1. 使用With ... End With
  2. 使用Call

我认为您遇到了问题,因为您正在尝试使用 C# 样式创建对象的实例,而不是在链接方法调用之前对其进行分配。

您的代码变为:

Dim name As String = "hello"

If CType(My.Application.OpenForms(name), Faker) Is Nothing Then
    With New Faker() With {.Name = name, .Title = String.Format("{0} - ID:{1}", "hello", Me.ClassClient.ClientAddressID)}

    .Show()
End If

Dim name As String = "hello"

If CType(My.Application.OpenForms(name), Faker) Is Nothing Then
    Call New Faker() With {.Name = name, .Title = String.Format("{0} - ID:{1}", "hello", Me.ClassClient.ClientAddressID)}.Show()

End If