我的代码中有一个Player类,我想通过将对象的名称创建为Player_1,Player_2 ...来初始化其对象。我只想在运行时在字符串变量“ Object_name”中生成对象名称,并且Object_name的值应类似于Player_1,Player_2,Player_3 ...
Private Function SaveTo_Player_Class_Object(ds)
For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim Object_name As String = "Player_" + Convert.ToString(Player_Class.Total_Players + 1)
Object_name = New Player_Class()
Object_name.Name = ds.Tables(0).Rows(j)(0).ToString()
Object_name.District_State_Nation = ds.Tables(0).Rows(j)(1).ToString()
Object_name.Year_Of_Birth = ds.Tables(0).Rows(j)(2).ToString()
Object_name.Weight = ds.Tables(0).Rows(j)(3).ToString()
Next
End Function
但是我在VB编辑器中遇到错误“类型Player_Class的值不能转换为字符串”
在将As String更改为As Object
Private Function SaveTo_Player_Class_Object(ds)
For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim Object_name As Object = "Player_" + Convert.ToString(Player_Class.Total_Players + 1)
Object_name = New Player_Class()
Object_name.Name = ds.Tables(0).Rows(j)(0).ToString()
Object_name.District_State_Nation = ds.Tables(0).Rows(j)(1).ToString()
Object_name.Year_Of_Birth = ds.Tables(0).Rows(j)(2).ToString()
Object_name.Weight = ds.Tables(0).Rows(j)(3).ToString()
Next
End Function
在这种情况下,对象名称是Object_name,而不是Player_1
我的两个版本的代码都无法正常工作。
答案 0 :(得分:0)
您正在将Object_name
定义为String
。在VB.NET(或C#)中,将变量定义为特定类型时,该类型不能更改。在当前范围内,它必须始终为String
。
因此,当您尝试将New Player_Class()
分配给Object_name
时,VB.NET告诉您不能将其转换为String
。
我觉得您正在尝试定义名称为Player_1
,Player_2
,Player_3
等的新变量,以便可以在代码的其他位置使用该名称
你不能那样做。
VB.NET是一种静态类型的语言。您要使用的每个变量都必须在编译时定义。您无法在运行时定义新变量。
但是,您可以使用数组,列表,字典或许多其他类型在运行时保存播放器变量。
您可以执行以下操作:
Private Function SaveTo_Player_Class_Object(ds As DataSet) As List(Of Player_Class)
Dim players = New List(Of Player_Class)
For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim p = New Player_Class()
p.Name = ds.Tables(0).Rows(j)(0).ToString()
p.District_State_Nation = ds.Tables(0).Rows(j)(1).ToString()
p.Year_Of_Birth = ds.Tables(0).Rows(j)(2).ToString()
p.Weight = ds.Tables(0).Rows(j)(3).ToString()
players.Add(p)
Next
Return players
End Function
现在您可以呼叫Dim players = SaveTo_Player_Class_Object(ds)
,然后可以像players(0).Name
这样访问每个玩家。
或者,您可以像这样使用Dictionary(Of String, Player_Class)
:
Private Function SaveTo_Player_Class_Object(ds As DataSet) As Dictionary(Of String, Player_Class)
Dim players = New Dictionary(Of String, Player_Class)
For j As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim p = New Player_Class()
p.Name = ds.Tables(0).Rows(j)(0).ToString()
p.District_State_Nation = ds.Tables(0).Rows(j)(1).ToString()
p.Year_Of_Birth = ds.Tables(0).Rows(j)(2).ToString()
p.Weight = ds.Tables(0).Rows(j)(3).ToString()
players.Add("Player_" + Convert.ToString(Player_Class.Total_Players + 1), p)
Next
Return players
End Function
现在您可以呼叫Dim players = SaveTo_Player_Class_Object(ds)
,然后可以像players("Player_42").Name
这样访问每个玩家。
这有意义吗?