2017-09-03 60 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);