1

我需要根据文本文件中的内容设置一个变量。

文本文件是这样设置的:

AK_47_M,30Rnd_762x39_AK47
AK_47_S,30Rnd_762x39_AK47
AKS_74_Kobra,30Rnd_545x39_AK
bizon_silenced,64Rnd_9x19_SD_Bizon
M1014,8Rnd_B_Beneli_74Slug
M16A2,30Rnd_556x45_Stanag

依此类推……你会注意到第一部分是武器类名,第二部分是弹药类型的类名。

我的表单上有一个名为 box_weapon 的组合框,它从同一个文本文件中读取,并通过运行以下代码创建该行的所有第一部分的数组:

string[] weaponsArray = File.ReadAllLines("weapons.txt");
            foreach (var line in weaponsArray)
            {
                string[] tokens = line.Split(',');
                box_pw.Items.Add(tokens[0]);
            }

总结一下。我需要某种“如果 box_weapon = linePosition1; ammoType = linePosition2”

4

3 回答 3

3

试试这个

StreamReader reader = File.OpenText(@"C:\weapons.txt");
while (!reader.EndOfStream)
{
    string currentLine = reader.ReadLine();
    string[] words = currentLine .Split(",");
    if (this.box_weapon.SelectedItem.ToString()  == words[0])
    {
     ammoType = words[1];
    }

}
于 2012-11-23T23:51:17.463 回答
0
public class Weapons
{
    public string AK_47_M;
    public string AK_47_S;
    public string AKS_74_Kobra;
    public string bizon_silenced;
    public string M1014;
    public string M16A2;
}

Weapons weapons = (new JavascriptSerializer())
    .Deserialize<Weapons>( "{" + 
         String.Join(",", File.ReadAllLines("weapons.txt")
                              .Select(x => x.Replace(",",":"))
                              .ToArray()) + 
    "}" );

String AK = weaponsObj.AK_47_M;
于 2012-11-24T00:19:29.947 回答
0

不要添加Strings到您的组合框中。添加“武器”!

Public Class Form1

Private Weapons As New List(Of Weapon)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    With Weapons
        .Add(New Weapon("M16", ".223"))
        .Add(New Weapon("AK74", "7.62"))
        .Add(New Weapon("Catapult", "Pumpkin"))
    End With
    Me.ComboBox1.DataSource = Weapons
End Sub

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1.SelectedItem IsNot Nothing Then
        Dim w As Weapon = DirectCast(ComboBox1.SelectedItem, Weapon)
        Debug.Print("A {0} needs some {1} to be effective!", w.Name, w.Ammo)
    End If
End Sub
End Class

Public Class Weapon

Public Name As String
Public Ammo As String

Public Sub New(Name As String, Ammo As String)
    Me.Name = Name
    Me.Ammo = Ammo
End Sub

Public Overrides Function ToString() As String
    Return Me.Name
End Function

End Class
于 2012-11-24T00:22:51.747 回答