编程语言
首页 > 编程语言> > 如何从C#中的未知枚举中获取值?

如何从C#中的未知枚举中获取值?

作者:互联网

我实际上正在编写一个可扩展对象的deepToString-Method.这使用反射来获取对象的每个属性,并为此属性调用deepToString-Method.除Enums之外,一切都正常.如果我尝试将PropertyInfo.GetValue()与枚举一起使用,则它将始终返回零.

如何获得真正的int值?我想念什么?

解决方法:

foreach (PropertyInfo propertyInfo in your_class.GetType().GetProperties())
{
  if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
  {
    foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
    {
      ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
      //... use it
    }
  }
}

我必须补充,反射是邪恶的.真正需要它的场合很少.

标签:reflection,enums,c
来源: https://codeday.me/bug/20191201/2083280.html