vb.net 从自定义类初始化数组或字符串的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17323498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:02:53  来源:igfitidea点击:

Initialize Property of array or strings from custom class

arraysvb.netstringinitialization

提问by Mr Dog

I have tried a number of different things but cant seem to find the right syntax to initialize this array of strings.

我尝试了许多不同的东西,但似乎找不到正确的语法来初始化这个字符串数组。

I have it in a custom class

我在一个自定义类中有它

Public Class datahere

    Public Property Name As String
    Public Property parameters() As String
    Public Property elem As XElement

End Class

and I declare it like so

我这样声明

Dim xdata(newdata.Count) As datahere

But not sure how to go about using it. I use the other variables like so

但不确定如何使用它。我像这样使用其他变量

xdata(3).Name = "TEST"

回答by matzone

Try like this ..

像这样尝试..

First change like this

第一次改成这样

Public Property parameters As List(Of String)

And create array class

并创建数组类

Dim ListDH as List(Of DataHere)

Dim par as New Parameter
par.Add("Any value")

Dim DH as New DataHere

DH.Name = "Test"
DH.Parameter = par
DH.Property = ....

ListDH.Add(DH)

So you can access if by

所以你可以访问 if

ListDH(0).Name          '-----> to get Name of first array ("TEST")

ListDH(0).Parameter(0)  '-----> to get First array of Parameter from the list ("Any value")

回答by N0Alias

Although I would recommend using a List(of String) for your Parameters Property, if you insist on using arrays you can do the following.

虽然我建议为您的参数属性使用 List(of String),但如果您坚持使用数组,您可以执行以下操作。

First change the parameters property to the following:

首先将参数属性更改为以下内容:

Public Property parameters As String()

Keep in mind that xdata(3).parameters(0) will be nothing. To change that you would specify the number of items in the array like so:

请记住, xdata(3).parameters(0) 将什么都不是。要更改它,您可以像这样指定数组中的项目数:

ReDim xdata(3).parameters(0)
'Give it a value
xdata(3).parameters(0) = "Test 1"

If you want to add additional items you have to redefine the array. To prevent losing your existing data use the Preserve Keyword:

如果要添加其他项目,则必须重新定义数组。为防止丢失现有数据,请使用保留关键字:

ReDim Preserve xdata(3).parameters(1)
'Give the second item in the array a value
xdata(3).parameters(1) = "Test 2"

To get your values is pretty straight forward:

要获得您的价值非常简单:

Dim strSecondParameters As Strign = xdata(3).parameters(1)