我正在尝试将数组元素分配给自动实现的属性,但它无法正常工作。
我尝试了什么:
Public Class A
Public Property A() as String = New() {"Hello", "Friend"}
End Class
和
Public Class A
Public Property A() as String = {"Hello", "Friend"}
End Class
但我总是得到错误,即类型1维数组的字符串的值不能转换为字符串。
有人可以帮我吗?
答案 0 :(得分:3)
你必须使用
Property A As String()
而不是
Property A() as String
否则编译器会假设string
而不是string()
。
这样可行:
Public Class Foo
Public Property A As String() = {"Hello", "Friend"}
End Class
当然你也可以使用构造函数:
Public Class Foo
Public Sub New()
A = {"Hello", "Friend"}
End Sub
Public Property A As String()
End Class
顺便说一句,有趣的是它适用于两种方式的字段:
Public B1() As String = {"Hello", "Friend"} ' compiles
Public B2 As String() = {"Hello", "Friend"} ' compiles
旁注:属性不应与类同名。因此,我已将该课程重新命名。