如何从静态类的静态属性中获取值?

本文关键字:获取 属性 静态 静态类 | 更新日期: 2023-09-27 18:05:05

我想知道下面班的人的名字。我可以得到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);                        
                }
            }
        }

edit将null == c更改为null != c以获得控制台。执行

如何从静态类的静态属性中获取值?

使用说明:

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

第一个null是属性的目标——它是空的,因为它是一个静态属性。第二个null表示没有任何索引器参数,因为这只是一个属性,而不是索引器。(它们是CLR的同一类成员)

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

然后我颠倒了与null比较的操作数的顺序,以及颠倒意义-如果您知道c为空,则不要试图打印出c.Name !在c#中,旧的c++习惯用法if (2 == x)避免意外赋值几乎总是没有意义的,因为if条件无论如何都必须是bool表达式。根据我的经验,大多数人认为变量放在第一位,常量放在第二位的代码更具可读性。

这是我使用的方法,我把它放入了自己的方法中。这将返回一个对象数组,这些对象是您传入的类型中静态可用的所有实例。不管原始类型是否是静态的,

using System;
using System.Linq;
using System.Reflection;
public static object[] RetrieveInstancesOfPublicStaticPropertysOfTypeOnType(Type typeToUse) {
     var instances = new List<object>();
     var propsOfSameReturnTypeAs = from prop in typeToUse.GetProperties(BindingFlags.Public | BindingFlags.Static)
                                       where prop.PropertyType == typeToUse
                                       select prop;
     foreach (PropertyInfo props in propsOfSameReturnTypeAs) {
             object invokeResult = typeToUse.InvokeMember(
                      props.Name, 
                      BindingFlags.GetProperty, 
                      null,
                      typeToUse, 
                      new object[] { }
             );
             if (invokeResult != null) {
                      instances.Add(invokeResult);
             }
     }
     return instances.ToArray();
}