2017-09-03 104 views
1

我在2个字符串变量中拥有属性名称和值。当属性类型是例如字符串时很容易设置:如何将值设置为C#中的枚举属性

prop.SetValue(P, Value, null); 

但是如何枚举类型? 请看下面的例子:

public enum enmSex { Male, Female, Trans }; 
    public enum enmMaritalStatus { Married, Single, Divorced, Widowed }; 

    private class Person 
    { 
     public string GivenName { get; set; } 
     public int Age { get; set; } 
     public double Weight { get; set; } 
     public enmSex Sex { get; set; } 
     public enmMaritalStatus MaritalStatus { get; set; } 
    } 

    private List<Person> People = new List<Person>(); 

    private void SetPersonProperty(string GivenName, string Property, string Value) 
    { 
     Person P = People.Where(c => c.GivenName == GivenName).First(); 
     PropertyInfo prop = typeof(Person).GetProperties().Where(p => p.Name == Property).First(); 
     if (prop.PropertyType == typeof(double)) 
     { 
      double d; 
      if (double.TryParse(Value, out d)) 
       prop.SetValue(P, Math.Round(d, 3), null); 
      else 
       MessageBox.Show("\"" + Value + "\" is not a valid floating point number."); 
     } 
     else if (prop.PropertyType == typeof(int)) 
     { 
      int i; 
      if (int.TryParse(Value, out i)) 
       prop.SetValue(P, i, null); 
      else 
       MessageBox.Show("\"" + Value + "\" is not a valid 32bit integer number."); 
     } 
     else if (prop.PropertyType == typeof(string)) 
     { 
      prop.SetValue(P, Value, null); 
     } 
     else if (prop.PropertyType.IsEnum) 
     { 
      prop.SetValue(P, Value, null); // Error! 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     People.Add(new Person { GivenName = "Daniel" }); 
     People.Add(new Person { GivenName = "Eliza" }); 
     People.Add(new Person { GivenName = "Angel" }); 
     People.Add(new Person { GivenName = "Ingrid" }); 

     SetPersonProperty("Daniel", "Age", "18"); 
     SetPersonProperty("Eliza", "Weight", "61.54442"); 
     SetPersonProperty("Angel", "Sex", "Female"); 
     SetPersonProperty("Ingrid", "MaritalStatus", "Divorced"); 
     SetPersonProperty("Angel", "GivenName", "Angelina"); 
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     foreach (Person item in People) 
      MessageBox.Show(item.GivenName + ", " + item.Age + ", " + 
       item.Weight + ", " + item.Sex + ", " + item.MaritalStatus); 
    } 
+0

怎么样'MartialStatus .Divorced'?你传入一个字符串而不是一个枚举,你可以使用Enum.Parse。为什么你使用反射方式,而不是直接在'person.Sex = Sex.Femail'中的实例上设置属性?顺便说一句,它是_female_,当然不是_femail_。 – oerkelens

+0

显然你需要['Enum.Parse'](https://msdn.microsoft.com/en-us/library/essfb559(v = vs.110).aspx)或类似的,例如'prop.SetValue(P ,Enum.Parse(prop.PropertyType,Value),null);' –

+0

这只是我为我的问题准备的一个例子。我的代码有一个非常大的类,有几个枚举类型,并且将它带到这里非常复杂。如果您只复制并粘贴此代码,则会遇到该错误。我只是不知道如何解决它。我也不能对我复杂的代码做很多修改。另外我不知道如何使用Enum.Parse。我真的想要一个工作解决方案。谢谢。 –

回答

0

您需要解析字符串中Value成所需的枚举类型:

var enumValue = Enum.Parse(prop.PropertyType, Value); 

然后把它传递给SetValue()

prop.SetValue(P, enumValue, null);