C# 将值赋给bool';它基于复选框
在我的代码中,我有一个名为“teacher”的类,其中包含一些数组:C# 将值赋给bool';它基于复选框,c#,arrays,list,initialization,boolean,C#,Arrays,List,Initialization,Boolean,在我的代码中,我有一个名为“teacher”的类,其中包含一些数组: public class teacher { //monday public bool[] mon = new bool[11]; //tuesday public bool[] tue = new bool[11]; //wednesday public bool[] wed = new bool[11];
public class teacher
{
//monday
public bool[] mon = new bool[11];
//tuesday
public bool[] tue = new bool[11];
//wednesday
public bool[] wed = new bool[11];
//thursday
public bool[] thu = new bool[11];
//fri
public bool[] fri = new bool[11];
};
还有一份教师名单:
List<teacher> teachers = new List<teacher>();
但它不允许我访问mon[0],因为它说“无效的初始化器成员声明器”。关于如何分配值有什么想法吗
我还将最后一段代码更改为:
mon = {checkBox25.Checked, checkBox26.Checked, checkBox27.Checked, checkBox28.Checked, checkBox29.Checked, checkBox30.Checked, checkBox31.Checked, checkBox32.Checked, checkBox33.Checked, checkBox34.Checked, checkBox35.Checked},
但现在它说它不能用集合初始值设定项初始化bool[]类型的对象
如果有人知道如何处理这个问题,我将非常感激。您的最后两个部分在初始值设定项中不起作用的原因是您需要这样做:
teachers.Add(new teacher
{
mon = new[]
{
checkBox25.Checked,
checkBox26.Checked,
checkBox27.Checked,
checkBox28.Checked,
checkBox29.Checked,
checkBox30.Checked,
checkBox31.Checked,
checkBox32.Checked,
checkBox33.Checked,
checkBox34.Checked,
checkBox35.Checked
},
// etc...
});
您需要在其中使用new[]
来构造bool的新数组,然后初始值设定项列表指定其内容
也就是说,您最好将复选框控件收集在一起(以数组或列表等形式),以便在作业中查询它们,例如:
teachers.Add(new teacher
{
mon = monCheckBoxes.Select(cb => cb.Checked).ToArray(),
tue = // etc...
});
显然,您的初始值设定项答案是正确的。我还怀疑op的方法有缺陷。每天都有bool[11];我想知道op是否更愿意将bools封装到DayMeta(或者任何合适的名称,DayConditionsList,dayoptioncollection,等等)中。我打赌每个布尔都有一个意义,我会将它们表示为布尔字段/属性。在每个老师的每一天中声明一个DayMeta
。谢谢你们,我发现你们的两个答案都非常有用。是的,我是一个新手,自学成才,有时会犯上面提到的愚蠢错误。也就是说,我很高兴仍然有像你这样的人帮助新手:)
teachers.Add(new teacher
{
mon = monCheckBoxes.Select(cb => cb.Checked).ToArray(),
tue = // etc...
});