我正在尝试获取下课人员的姓名。我可以很好地获取PropertyInfo的列表,表明People有Bob和Sally,但是我没有引用Bob和Sally。我怎么做?

        public static class People
        {
            public static Person Bob { get; }
            public static Person Sally { get; }
        }


        PropertyInfo[] properties = typeof(People).GetProperties();

        foreach (PropertyInfo info in properties)
        {
            if (info.PropertyType == typeof(Person))
            {
                // how do I get a reference to the person here?
                Person c = info.GetValue(?????, ?????) as Person;
                if (null != c)
                {
                    Console.WriteLine(c.Name);
                }
            }
        }


编辑将null == c更改为null!= c以使console.writeline执行

最佳答案

使用:

Person c = (Person) info.GetValue(null, null);
if (c != null)
{
    Console.WriteLine(c.Name);
}


第一个null为属性的目标-之所以为null是因为它是静态属性。第二个null表示没有索引器参数,因为这只是一个属性,而不是索引器。 (他们是CLR的成员。)

我已经将结果的使用从as更改为强制类型转换,因为您期望结果是Person,因为您已经检查了属性类型。

然后,我将操作数的顺序与null进行了颠倒,并且颠倒了意义-如果您知道c.Name为null,就不想尝试打印c!在C#中,避免意外分配的if (2 == x)的旧C ++习惯用法几乎总是毫无意义的,因为if条件无论如何都必须是bool表达式。以我的经验,大多数人会发现代码更易读,变量第一和常量第二。

10-04 23:29
查看更多