0

我试图通过查看另一个对象中保存的字符串值来在自定义对象上设置自定义枚举属性,但我不断收到错误“无法通过表达式引用类型”。

到目前为止我已经尝试过

rec.Course  = (CourseEnum)Enum.Parse(typeof(CourseEnum), rr.course);

其中 rec.Course 需要 CourseEnum 枚举的成员,而 rr.course 是一个字符串。

我还尝试执行一个 switch 语句,其中rr.course检查了 的值(它只能是某些值)但得到相同的结果

枚举定义如下:

public enum CourseEnum
    {
        [StringValue("Starters")]
        Starters,
        [StringValue("Main Course")]
        MainCourse,
        [StringValue("Desserts")]
        Desserts
    };

public class StringValue : System.Attribute
{
    private string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    {
        string output = null;
        Type type = value.GetType();

        //Check first in our cached results...

        //Look for our 'StringValueAttribute' 

        //in the field's custom attributes

        FieldInfo fi = type.GetRuntimeField(value.ToString());
        StringValue[] attrs =
           fi.GetCustomAttributes(typeof(StringValue),
                                   false) as StringValue[];
        if (attrs.Length > 0)
        {
            output = attrs[0].Value;
        }

        return output;
    }
}
4

2 回答 2

0

我可以在您的代码中看到您Enum.Parse与 CourseEnum 一起使用,我认为应该是recipeCourse这样。

我在您的示例代码中找不到任何CourseEnum定义 4 的地方。

于 2012-09-02T13:13:46.810 回答
0

@Hans Kesting 说,答案就在这里:为什么不能通过表达式引用类型?

问题是使用具有枚举类型本身的枚举类型的字段。

于 2013-04-07T15:43:54.913 回答