以下程序在TextBox中输入以逗号分隔的整型数,而且可以输入任意数量的整型数。
(1)在窗体上布置一个TextBox和一个Button
(2)窗体代码Form1.cs如下
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// 存放输入的整型数组
int[] a;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == string.Empty) return;
string[] numbers = textBox1.Text.Split(',');
List<int> list = new List<int>();
foreach (var s in numbers)
{
int v;
if (int.TryParse(s, out v))
{
list.Add(v);
}
}
// 将集合转换为数组
a = list.ToArray();
}
}
}
查看数组a