C# 使用foreach迭代时跳过类的某些属性
我想在遍历Student类时跳过ID属性,但对于某些循环,该属性必须是可浏览的C# 使用foreach迭代时跳过类的某些属性,c#,C#,我想在遍历Student类时跳过ID属性,但对于某些循环,该属性必须是可浏览的 internal class Student { [DisplayName("N")] public int ID { get; set; } [DisplayName("Name")] public string FirstName { get; set; } [DisplayName("Surname")] public string LastName { g
internal class Student
{
[DisplayName("N")]
public int ID { get; set; }
[DisplayName("Name")]
public string FirstName { get; set; }
[DisplayName("Surname")]
public string LastName { get; set; }
[DisplayName("ID Number")]
public string IDNumber { get; set; }
[DisplayName("Mobile Number")]
public string Mobile { get; set; }
[DisplayName("Class")]
public byte Grade { get; set; }
[Browsable(false)]
public int StatusID { get; set; }
}
下面是遍历学生类属性的代码
int num = 1;
PropertyInfo[] properties = typeof(Student).GetProperties();
foreach (PropertyInfo property in properties)
{
property.SetValue(newStudent, Convert.ChangeType(_textBoxes[num].Text, property.PropertyType));
num++;
}
其中_textboxs[num]。文本是字符串
我想在遍历Student类时跳过ID属性
可能考虑创建一个VIEW模型,然后只需要像
所需的属性public class StudentViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string IDNumber { get; set; }
public string Mobile { get; set; }
public byte Grade { get; set; }
public int StatusID { get; set; }
}
您只需检查属性的名称:
int num = 1;
PropertyInfo[] properties = typeof(Student).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.Name != nameof(Student.ID))
{
property.SetValue(newStudent, Convert.ChangeType(_textBoxes[num].Text, property.PropertyType));
}
num++;
}
您可以使用
Linq
提供的Where
来过滤属性
foreach (PropertyInfo property in properties.Where(x => x.Name != nameof(Student.ID)))
{
property.SetValue(newStudent, Convert.ChangeType(_textBoxes[num].Text, property.PropertyType));
num++;
}
迭代的代码和跳过属性的lgic在哪里?请注意,类的“迭代属性”不是“标准”行为,它需要一些自定义代码(例如使用反射):将跳过逻辑与必须编写的(必需)代码放在一起编辑主题,因此,我想这更容易理解,是这样做的,但我不想使用几乎相同的新类,我可以逐个设置这些属性,如:
newStudent.Firstname=\u textboxs[0]。text
,但如果有办法让foreach跳过我不想选择的属性,我会感兴趣。谢谢,这样做可能会成功。