首先我会说我是编程初学者,但我想制作一个工作程序来随机化员工的姓名。仅在复选框中选中的名称。目前,它会从所有名称或最近选择的名称中随机分配我。目前名称标记为:N1、N2、N3、N4、N5: 我的代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MNW_v._1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void N1_CheckedChanged(object sender, EventArgs e)
{
}
private void N2_CheckedChanged(object sender, EventArgs e)
{
}
private void N3_CheckedChanged(object sender, EventArgs e)
{
}
private void N4_CheckedChanged(object sender, EventArgs e)
{
}
private void N5_CheckedChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string[] tablica = new string[] { N1.Text, N2.Text, N3.Text, N4.Text, N5.Text };
Random rn = new Random();
int obj = rn.Next(0, tablica.Length);
Console.Write(obj);
if (N1.Checked)
{
MessageBox.Show(N1.Text);
}
else if (N2.Checked)
{
MessageBox.Show(N2.Text);
}
else if (N3.Checked)
{
MessageBox.Show(N3.Text);
}
else if (N4.Checked)
{
MessageBox.Show(N4.Text);
}
else if (N5.Checked)
{
MessageBox.Show(N5.Text);
}
}
}
}
我已经尝试过创建一个附加类,但似乎选中这些框不会影响程序的运行。
最佳答案
我宁愿有一个 CheckBox
数组,而不是它们的 Text
数组:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e) {
// So we have all CheckBoxes of interest in the collection (array)
// we can query
var boxes = new CheckBox[] {
N1, N2, N3, N4, N5
};
// How many checked CheckBoxes do we have
int count = boxes.Count(box => box.Checked);
// If we have at least one checked CheckBox, we can get random one
string randomName = count > 0
? boxes.Where(box => box.Checked).ElementAt(Random.Shared.Next(count)).Text
: ""; // If none of boxes has been checked
MessageBox.Show(randomName);
}
如果您的 .Net 版本不支持Random.Shared
,您可以使用字段:
using System.Linq;
...
private static readonly Random random = new Random();
private void button1_Click(object sender, EventArgs e) {
var boxes = new CheckBox[] {
N1, N2, N3, N4, N5
};
int count = boxes.Count(box => box.Checked);
string randomName = count > 0
? boxes.Where(box => box.Checked).ElementAt(random.Next(count)).Text
: "";
MessageBox.Show(randomName);
}
关于c# - 如何从复选框/Windows 窗体/C# 显示随机名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74914766/