迭代自身内部类的实例

时间:2014-04-06 20:37:01

标签: c# static static-members

(我没有创建这个,但我必须使用它)

class Person{

  public string Name {
    get;
    private set;
  }

  public static Person P1 = new Person("name1");
  public static Person A1 = new Person("aName1");
  public static Person ZX1 = new Person("NameZX");
  public static Person P2 = new Person("name2");
  .
  .
  public static Person P20 = new Person("name20");    
}

我需要遍历所有这些实例,我认为它涉及反射,但我不确定如何。

@ Selman22,谢谢,现在我必须循环通过这些人

forach(var p in persons)
{
}

但是pFieldInfo对象,如何将其更改回Person(投射无效)

2 个答案:

答案 0 :(得分:3)

您可以使用Reflection这样填写字段:

var persons = typeof(Person)
             .GetFields(BindingFlags.Public | BindingFlags.Static)
             .Where(x => x.Name.StartsWith("P"));

或者:

var persons = typeof(Person)
              .GetFields(BindingFlags.Public | BindingFlags.Static)
              .Where(x => x.GetValue(null) is Person);

foreach(var p in persons)
{
    var currentPerson = p.GetValue(null) as Person;
    ...
}

答案 1 :(得分:1)

你可以把它们全部放在数组中然后再做:

var people = new[]
{
    Person1,
    Person2,
    ...
    Person20
};

foreach (var person in people)
{
    ...
}