如何在VB.NET中通过数组访问类变量?
如果我有以下类别和声明:如何在VB.NET中通过数组访问类变量?,vb.net,class,Vb.net,Class,如果我有以下类别和声明: Public Class objLocation Public SysLocationId As String Public NameFull As String Public LatRaw As String Public LongRaw As String Public Active As Integer End Class dim lLocation as new objLocation 我可以访问每个变量,因此allocatio
Public Class objLocation
Public SysLocationId As String
Public NameFull As String
Public LatRaw As String
Public LongRaw As String
Public Active As Integer
End Class
dim lLocation as new objLocation
我可以访问每个变量,因此
allocation.SysLocationId
,等等。有没有其他方法,所以我可以通过索引访问每个变量,例如allocation(0)、allocation(1)等,这使我能够灵活地通过for next循环与相同类型的类进行比较,或者与其他源(如数据表)进行比较。否,你不能直接这样做
您必须使用反射来获取属性,但是您必须知道,返回的属性的顺序没有保证(如果您想对它们进行数字索引,这一点很重要)
因此,在处理属性(和索引)时,您必须保持排序顺序一致。是否要查找列表:
Dim LocationList As List<objLocation>;
For Each loc As objLocation In LocationList
loc.whatever
Next
抱歉,如果VB语法不正确…我最近一直在做C#,没有VB你可以按如下方式来做。它是C#,与在VB中使用索引器有些不同,但您应该完全能够在VB中使用它
public class ObjLocation
{
private String[] Properties = new String[5];
public const Int32 IndexSysLocationId = 0;
public const Int32 IndexNameFull = 1;
public const Int32 IndexLatRaw = 2;
public const Int32 IndexLongRaw = 3;
public const Int32 IndexActive = 4;
// Repeat this for all properties
public String SysLocationId
{
get { return this.Properties[ObjLocation.IndexSysLocationId]; }
set { this.Properties[ObjLocation.IndexSysLocationId] = value; }
}
public String this[Int32 index]
{
get { return this.Properties[index]; }
set { this.Properties[index] = value; }
}
}
现在,对象的属性与以前一样,但存储在数组中,您也可以通过索引器访问它们。如果您的目标是比较,通常您要做的是实现
IComparable
接口或重载
,没有内置的语言支持。但是,可以通过在类上创建默认索引器属性来模拟这种情况
Public Class objLocation
...
Default Public ReadOnly Property Indexer(ByVal index As Integer)
Get
Select Case index
Case 0
Return SysLocationId
Case 1
Return NameFull
Case 2
Return LatRaw
Case 3
Return LongRaw
Case 4
Return Active
Case Else
Throw New ArgumentException
End Select
End Get
End Property
然后您可以按如下方式使用它
Dim x As objLocation = GetObjLocation
Dim latRaw = x(2)
我在公共结构中实现的此方法用于返回存储在结构中的字符串变量数组:
Public Shared Function returnArrayValues() As ArrayList
Dim arrayOutput As New ArrayList()
Dim objInstance As New LibertyPIMVaultDefaultCategories()
Dim t As Type = objInstance.GetType()
Dim arrayfinfo() As System.Reflection.FieldInfo = t.GetFields()
For Each finfo As System.Reflection.FieldInfo In arrayfinfo
Dim str As String = finfo.GetValue(objInstance)
arrayOutput.Add(str)
Next
Return arrayOutput
End Function
将其放在结构或类中。也许这个示例代码有帮助。类名上的匈牙利符号。。。那是不对的。类不是对象!匈牙利语在.Net中的任何地方都是不正确的。所有这些都是很好的答案,但我认为这一个最适合我想做的事情,即按索引循环一个类变量,获取值,然后将它们分配给数据库。
Public Shared Function returnArrayValues() As ArrayList
Dim arrayOutput As New ArrayList()
Dim objInstance As New LibertyPIMVaultDefaultCategories()
Dim t As Type = objInstance.GetType()
Dim arrayfinfo() As System.Reflection.FieldInfo = t.GetFields()
For Each finfo As System.Reflection.FieldInfo In arrayfinfo
Dim str As String = finfo.GetValue(objInstance)
arrayOutput.Add(str)
Next
Return arrayOutput
End Function