c# - 设置由字符串给出的枚举类型的属性

标签 c# properties enums

我类有一些枚举,看起来像这个:

public enum A { A1, A2 }
public enum B { B1, B2 }

问题是当我尝试从 XML 文件中读取项目时(每个字段由属性名称和属性值给出 - 均为字符串)。

现在我得到了我的方法,它是设置单个属性的值(只有 isEnum 检查的部分)。

public A classfield
{
  get;
  set;
}
public bool DynamicallySetItemProperty(string name, string value)
{
  // value = "A1" or "A2"; - value given in string.
  // name = "classfield"; - name of property.
  PropertyInfo p = this.GetType().GetProperty(name);
  if (p.PropertyType.IsEnum)
  {
    var a = (A) Enum.Parse(typeof(A), value);
    p.SetValue(this, a);
  }
  return true;
}

但在这一个中我不检查字段是 A 还是 B 枚举。

有没有办法让我的方法检查枚举类型,然后将我的字符串解析为这个枚举,像这样:

public bool DynamicallySetItemProperty(string name,string value)
{
  PropertyInfo p = this.GetType().GetProperty(name);
  if (p.PropertyType.IsEnum)
  {    
    var a = (p.GetType()) Enum.Parse(typeof(p.GetType()), value); // <- it doesn't work
    p.SetValue(this, a);
  }
  return true;
}

所以我需要检查属性的枚举类型,然后在不使用 if/else 或 switch 语句的情况下将我的字符串值解析为这个枚举类型(当我有很多枚举类型时这是有问题的)。有什么简单的方法吗?

最佳答案

不需要进一步检查类型。 Enum.Parse()将类型作为第一个参数,您需要的类型是 p.PropertyType (因为这是 属性的类型SetValue() 无论如何都将 object 作为值的参数,因此无需转换 Enum.Parse() 的返回值:

PropertyInfo p = this.GetType().GetProperty(name);
if (p.PropertyType.IsEnum)
   p.SetValue(this, Enum.Parse(p.PropertyType, value));

注意 p.GetType()返回 Type PropertyInfo 的实例,不是枚举类型!

关于c# - 设置由字符串给出的枚举类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851734/

相关文章:

java - 如何读取Spring Boot application.properties?

c# - 如何修复网站上的 Gecko 29.0 错误 (sec_error_unknown_issuer)?

c# - 如何模拟 Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.CryptographyManager

vb.net - Visual Studio 没有选项可以在调试和发布之间进行选择

python - 修复 'new enumerations must be created as'

c# - 如何将查找表映射到枚举?

swift - 是否可以通过扩展将关联值添加到现有的 Swift 枚举中?

c# - 如何在C#中读取图像和文本值?

c# - 带有按钮的 ListView 中的 UWP/MVVM 数据绑定(bind)不起作用

c# - 缓存属性 : Easier way?