我正在尝试获取以下类(class)中人员的姓名。我可以很好地获得 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
c
为空!在 C# 中,用于避免意外赋值的 if (2 == x)
的旧 C++ 习语几乎总是毫无意义的,因为 if
条件必须是 bool
表达式。根据我的经验,大多数人发现首先使用变量,然后使用常量的代码更具可读性。
关于c# - 如何从静态类的静态属性中获取值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7001892/