-2

我有一个保存每个按钮特定坐标的二维字符串数组

string[,] gridPass = new string[20, 20];


    private void Form1_Load(object sender, EventArgs e)
    {
        foreach (int row in Enumerable.Range(0, 20))
        {
            foreach (int col in Enumerable.Range(0, 20))
            {

                Button b = new Button();
                b.Size = new System.Drawing.Size(30, 30);
                b.Location = new Point(row * 30, col * 30);
                gridPass[row, col] = row.ToString() + " - " + col.ToString();
                b.Tag =  gridPass[row, col];
                b.Text = gridPass[row, col];
                this.Controls.Add(b);
                b.Click += new EventHandler(AttackHandler);
            }


        }

当我在按钮上使用事件处理程序进行攻击时

private void AttackHandler(object sender, EventArgs e)
        {
            Button clickedButton;
            string tagValue = "";

            clickedButton = (Button)sender;
            tagValue = (string)clickedButton.Tag;
            theSea.attackLocation(tagValue);

        }

显然,无论按钮的坐标是什么,它都会发送一个像 0 - 1 或 8 - 4 这样的字符串。当我将该字符串传递给我的 Sea 类中的 attackLocation 方法时,我希望能够提取这两个数字以使用我的 Sea 类中的数组来引用它们,以查看那里是否有船。我需要那些 X 和 Y 值来引用另一个数组中完全相同的位置。所以我可以做类似的事情。

public void attackLocation(string attackCoords)
    {
        MessageBox.Show("Attacking " + attackCoords);
        x = however to convert it back;
        y = however to convert it back;
        foreach (Ship s in shipList)
        {
            if (grid[x,y] == 0)
            {
                MessageBox.Show("Attacked this block before."); 
            }
4

3 回答 3

3

创建一个类来保存行和列值并将 设置Tag为该对象。然后你就不需要进行字符串转换了。

class SeaPoint
{
  public int Row { get; set; }
  public int Column { get; set; }
}

在负载中:

        foreach (int col in Enumerable.Range(0, 20))
        {
            Button b = new Button();
            b.Size = new System.Drawing.Size(30, 30);
            b.Location = new Point(row * 30, col * 30);
            gridPass[row, col] = row.ToString() + " - " + col.ToString();
            b.Tag =  new SeaPoint() { Row = row, Column = col }; // <---  Changed.
            b.Text = gridPass[row, col];
            this.Controls.Add(b);
            b.Click += new EventHandler(AttackHandler);
        }

和攻击处理器:

private void AttackHandler(object sender, EventArgs e)
{
    Button clickedButton = (Button)sender;
    var seaPoint = (SeaPoint)clickedButton.Tag; // <-- Changed
    theSea.attackLocation(seaPoint);  // rewrite attackLocation to accept a SeaPoint.
}
于 2013-01-24T05:20:29.963 回答
0

您可以使用String.Split来提取连字符分隔的值并在它们上应用String.Trim以删除空格,然后再将其传递给int.Parse以将字符串转换为数字。

//b.Tag =  "0 - 1";    
string []arr = b.Tag.ToString().Split('-');    
int num1 = int.Parse(arr[0].Trim());
int num2 = int.Parse(arr[1].Trim());
于 2013-01-24T05:17:59.763 回答
0

制作这个正则表达式:

new Regex(@"(\d+) - (\d+)")

在要从中提取数字的字符串上使用正则表达式的匹配:

http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx

它将返回一个 Match 对象,该对象将包含两个组(假设我记得组和捕获之间的区别......)。组的值将是两个整数的字符串表示。int.Parse() 他们。

于 2013-01-24T05:19:21.077 回答