我有一个双维字符串数组,用于保存每个按钮特定的坐标
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.");
}
答案 0 :(得分: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);
}
和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.
}
答案 1 :(得分: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());
答案 2 :(得分:0)
制作这个正则表达式:
new Regex(@"(\d+) - (\d+)")
对要从中提取数字的字符串使用正则表达式的匹配:
http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx
它将返回一个Match对象,它将包含两个组(假设我记住组之间的区别并且捕获正确...)。组的值将是两个整数的字符串表示。 int.Parse()他们。