带有枚举数组的 C# 反射

标签 c# .net reflection enums

我有一个带有自定义枚举的类:

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

我的类(class)

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

这可能吗?

最佳答案

下面应该做你想做的。

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

关于带有枚举数组的 C# 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242480/

相关文章:

java - 实例化类型参数的对象

c# - 将字节数组从 Unity C# 传递到 C++ 插件

C# DateTime.TryParseExact 带可选参数

c# - WPF 列表框项目消耗太多内存

c# - 多个使用 block c#

c# - WCF NetTcpBinding - 来自 Microsoft 教程 - 超时

Java:确定静态方法是从实例调用还是静态调用

c# - 从反射方法 C# 中获取值

c# - 如何将以毫秒为单位的日期时间插入到 Access 数据库中?

c# - 解析 Datetime c# 的奇怪结果