我不确定适当的搜索字词所以请关闭并指出我是否重复,如果是这样的话。
我的结构有多个变量。我已经创建了一个结构类型的数组。我已经将数据添加到数组的一些索引中。我现在想根据变量的名称选择一个特定的变量。
他是结构的一个例子:
structure struc
dim name as string
dim lvl as integer
dim capacity as integer
end structure
阵列减速:
dim vills(3) as struc
答案 0 :(得分:2)
您应该使用公共字段,而不是变量实际上根据MSDN您的术语是正确的,您唯一缺少的是访问修饰符即
Public Structure Struc
Public Name As String
Public Lvl As Integer
Public Capacity As Integer
End Structure
目前您的变量是私有的,这意味着他们无法从Structure
外部访问。
查看您的评论,看起来您试图通过名称动态来访问该属性,而不是在编译时知道它。有几种方法可以做到这一点,其中大多数涉及一些Reflection。
你或许应该看看ExpandObject - 它实际上是一个具有普通类型对象特征的键/值字典,因此你可以获得两全其美的好处,例如。
Dim struct As Object = New ExpandoObject()
struct.name = "SomeValue"
struct.lvl = 3
struct.capacity = 100
Console.WriteLine(struct["name"])
Console.WriteLine(struct["lvl"])
答案 1 :(得分:1)
我真的认为如果这是一个重要而频繁的要求(按键查找元素),那么你应该三思而后行,将数组更改为Dictionary(Of string,struc)并使用类似的东西
Dim vills = new Dictionary(of String, struc)
Dim s = new struc()
s.name="k1"
s.lvl=1
s.capacity=1
z.Add(s.name, s)
....
struc c = vills("k1")
if(c IsNot Nothing) Then
Console.WriteLine(c.lvl.ToString())
End If
但如果您仍想使用数组,可以使用Linq
按名称搜索您的struc数组Structure struc
Public Dim name as string
Public Dim lvl as integer
Public Dim capacity as integer
End Structure
Sub Main
Dim vills(3) as struc
....
Dim c as struc = wills.Where(Function(x) (x.name="keyName")).Single()
if(c.name IsNot Nothing) then
Console.WriteLine("Found")
End If
End Sub
答案 2 :(得分:1)
正如托尼·霍普金森所提到的,可以通过反思来实现:
Public Class Form1
Structure struc
Dim name As String
Dim lvl As Integer
Dim capacity As Integer
End Structure
Dim vills(3) As struc
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To vills.Length - 1
vills(i).lvl = i * 10
Next
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fi As Reflection.FieldInfo
Dim fieldName As String = "lvl"
For i As Integer = 0 To vills.Length - 1
fi = vills(i).GetType.GetField(fieldName, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Public)
If Not IsNothing(fi) Then
Dim value As Object = fi.GetValue(vills(i))
Debug.Print(i & ": " & value.ToString)
End If
Next
End Sub
End Class
由您决定是否值得...