如何在C#中将值设置为枚举属性

时间:2017-09-03 15:45:50

标签: c# enums properties set

我在2个字符串变量中有属性名称和值。当属性类型为例如string:

时,很容易设置
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);
    }

1 个答案:

答案 0 :(得分:0)

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

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

然后将其传递给SetValue()

prop.SetValue(P, enumValue, null);