5

我有一个具有以下结构的学生班:

    public sealed class Student
    {
       public string Name {get;set;}
       public string RollNo {get;set;}
       public string standard {get;set;}
       public bool IsScholarshipped {get;set;}
       public List<string> MobNumber {get;set;}
    }

如何在数组中获取 Student 类的这些属性,例如

     arr[0]=Name;
     arr[1]=RollNo; 
      .
      .
      .
     arr[4]=MobNumber

并且这些属性的类型在单独的数组中,例如

     arr2[0]=string;
     arr2[1]=string;
      .
      .
      .
     arr2[4]=List<string> or IEnumerable

请用代码块解释一下。

4

4 回答 4

10
var type = model.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

这会给你一个数组PropertyInfo。然后,您可以这样做以获取名称:

properties.Select(x => x.Name).ToArray();
于 2012-11-22T12:49:37.740 回答
6

您可以使用反射:

foreach (PropertyInfo prop in typeof(Student).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
   '''
}
于 2012-11-22T12:47:43.757 回答
4

您可以对 的结果使用 LINQ GetProperty,如下所示:

var props = typeof(Student).GetProperties();
var names = props
    .Select(p => p.Name)
    .ToArray();
var types = props
    .Select(p => p.PropertyType)
    .ToArray();
for (int i = 0 ; i != names.Length ; i++) {
    Console.WriteLine("{0} {1}", names[i], types[i]);
}

这是打印的内容:

Name System.String
RollNo System.String
standard System.String
IsScholarshipped System.Boolean
MobNumber System.Collections.Generic.List`1[System.String]
于 2012-11-22T12:51:38.940 回答
0

为此可以使用运算符 [] 重载。可以使用 PropertyInfo 映射属性。

public sealed class Student
{
  public string Name { get; set; }
  public string RollNo { get; set; }
  public string Standard { get; set; }
  public bool IsScholarshipped { get; set; }
  public List<string> MobNumber { get; set; }

  public object this[int index]
  {
    get
    {
      // Note: This may cause IndexOutOfRangeException!
      var propertyInfo = this.GetType().GetProperties()[index];
      return propertyInfo != null ? propertyInfo.GetValue(this, null) : null;
    }
  }

  public object this[string key]
  {
    get
    {
      var propertyInfo = this.GetType().GetProperties().First(x => x.Name == key);
      return propertyInfo != null ? propertyInfo.GetValue(this, null) : null;
    }
  }
}

然后您可以通过这种方式使用该类:

var student = new Student { Name = "Doe, John", RollNo = "1", IsScholarshipped = false, MobNumber = new List<string>(new[] { "07011223344" }) };

var nameByIndex = student[0] as string;
var nameByKey = student["Name"] as string;

在msdn阅读有关 [] 运算符的更多信息。

请注意,以这种方式通过索引访问属性容易出错,因为属性的顺序很容易在没有任何控制的情况下更改。

于 2012-11-22T13:12:35.567 回答