我类有一些枚举,看起来像这个:
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/