【问题标题】:C# Reflection with enum array带有枚举数组的 C# 反射
【发布时间】:2013-01-09 17:03:38
【问题描述】:

我有一个自定义枚举类:

public enum Capabilities{
 PowerSave= 1,
 PnP =2,
 Shared=3, }

我的班级

public class Device
{
       ....
  public Capabilities[] DeviceCapabilities
  {
     get { // logic goes here}
  }

有没有办法在运行时使用反射来获取该字段的值? 我尝试了以下但得到空引用异常

PropertyInfo[] prs = srcObj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 foreach (PropertyInfo property in prs)
 {
     if (property.PropertyType.IsArray)
     {
         Array a = (Array)property.GetValue(srcObj, null);
     }    
 }

编辑:感谢您的回答,我真正需要的是一种无需指定枚举类型即可动态获取值的方法。 类似的东西:

string enumType = "enumtype"
var property = typeof(Device).GetProperty(enumType);

这可能吗?

【问题讨论】:

  • get values of this field 是什么意思?只需读取该数组并用它做你想做的事
  • 听起来像[Flags] 在这里很合适:msdn.microsoft.com/en-us/library/system.flagsattribute.aspx
  • 您是否有堆栈跟踪来验证 NullReferenceException 的来源?看起来它可能来自您的 DeviceCapabilities 属性中的逻辑,或者来自您对象中的另一个属性。

标签: c# .net reflection enums


【解决方案1】:

以下应该可以满足您的需求。

var property = typeof(Device).GetProperty("DeviceCapabilities");

var deviceCapabilities = (Capabilities[])property.GetValue(device);

请注意,Object PropertyInfo.GetValue(Object) 方法是 .NET 4.5 中的新方法。在以前的版本中,您必须为索引添加一个额外的参数。

var deviceCapabilities = (Capabilities[])property.GetValue(device, null);

【讨论】:

    【解决方案2】:

    这应该可行:

        var source = new Device();
    
        var property = source.GetType().GetProperty("DeviceCapabilities");
        var caps = (Array)property.GetValue(source, null);
    
        foreach (var cap in caps)
            Console.WriteLine(cap);
    

    【讨论】:

      【解决方案3】:

      如果你想枚举一个 Enum 的所有可能值并作为一个数组返回,那么试试这个辅助函数:

      public class EnumHelper {
          public static IEnumerable<T> GetValues<T>()
          {
              return Enum.GetValues(typeof(T)).Cast<T>();
          }
      }
      

      那么你可以简单地调用:

      Capabilities[] array = EnumHelper.GetValues<Capabilities>();
      

      如果这不是你所追求的,那么我不确定你的意思。

      【讨论】:

        【解决方案4】:

        你可以试试这个

        foreach (PropertyInfo property in prs)
        {
            string[] enumValues = Enum.GetNames(property.PropertyType);
        }
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-07-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-12
          • 1970-01-01
          • 2014-04-20
          相关资源
          最近更新 更多