2

我有一个自定义枚举类:

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

那可能吗?

4

4 回答 4

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);
于 2013-01-09T17:09:10.220 回答
0

这应该有效:

    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);
于 2013-01-09T17:08:18.893 回答
0

如果要枚举 Enum 的所有可能值并以数组形式返回,请尝试以下辅助函数:

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

然后你可以简单地调用:

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

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

于 2013-01-09T17:13:42.817 回答
0

你可以试试这个

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

希望能帮助到你。

于 2013-03-23T20:37:18.580 回答