使用foreach迭代时跳过类的一些属性

时间:2018-04-30 12:37:03

标签: 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 { 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; }
}

这里是迭代Student Class属性的代码

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是字符串

3 个答案:

答案 0 :(得分:0)

  

我希望在迭代Student class

时跳过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; }
}

答案 1 :(得分:0)

您可以查看酒店的名称:

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

答案 2 :(得分:0)

您可以使用Where提供的Linq来过滤属性。

foreach (PropertyInfo property in properties.Where(x => x.Name != nameof(Student.ID)))
{
    property.SetValue(newStudent, Convert.ChangeType(_textBoxes[num].Text, property.PropertyType));
    num++;
}