繁体   English   中英

如何从 static class 上的 static 属性中获取值?

[英]How do I get the values from static properties on a static class?

我正在尝试获取以下 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.= Z4A8A08F09D37B7087956Z9038 控制台。

利用:

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

第一个 null 用于属性的目标 - 这是 null 因为它是 static 属性。 第二个 null 是说没有任何索引器 arguments,因为这只是一个属性,而不是索引器。 (他们是 CLR 的同一种成员。)

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

然后,我颠倒了操作数的顺序,以便与 null 进行比较,以及颠倒感觉——如果你知道c.Name c null! 在 C# 中,使用if (2 == x)的旧 C++ 惯用语来避免意外分配几乎总是毫无意义的,因为if条件无论如何都必须是bool表达式。 根据我的经验,大多数人发现使用变量 first 和常量 second 的代码更具可读性。

这是我使用的方法,我已将其投入到自己的方法中。 这将返回一个对象数组,这些对象是您传入的类型中静态可用的所有实例。原始类型是否为 static 无关紧要。

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM