首页 > 解决方案 > 使用 foreach 迭代时跳过类的一些属性

问题描述

我想在遍历 Student 类时跳过 ID 属性,但是对于某些周期,该属性必须是可浏览的

 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++;
}

其中 _textBoxes[num].text 是字符串

标签: c#

解决方案


我想在遍历 Student 类时跳过 ID 属性

可能会考虑创建一个 ViewModel,然后只使用所需的属性,例如

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; }
}

推荐阅读