2014-06-30 70 views
2

我想將數組元素分配給自動實現的屬性,但它不工作。爲自動實現的屬性賦值爲字符串()

我的嘗試:

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 

但我總是得到錯誤字符串卡恩的類型一維數組的值不能轉換成字符串。

任何人都可以幫助我嗎?

回答

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 

附註:屬性不應該與該類名稱相同。所以我已經改名班了。

+1

謝謝,這是一個非常好的答案! – ruedi