简体   繁体   English

将字符串转换为自定义枚举

[英]Converting a string to a custom enum

I'm trying to set a custom enum property on a custom object by looking at a string value that is held in another object, but I keep getting the error "cannot reference a type through an expression." 我试图通过查看保存在另一个对象中的字符串值来在一个自定义对象上设置一个自定义枚举属性,但是我不断收到错误消息“无法通过表达式引用类型”。

so far I've tried 到目前为止,我已经尝试过

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

where rec.Course wants a member of the CourseEnum Enumeration, and rr.course is a string. 其中rec.Course希望是CourseEnum Enumeration的成员,而rr.course是字符串。

I also tried to do a switch statement where the value of rr.course is checked (there are only certain values it can be) but get the same result 我也尝试做一个switch语句,在其中检查rr.course的值(只能是某些值),但是得到相同的结果

the enum is defined as follows: 枚举定义如下:

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;
    }
}

I can see in your code that your using Enum.Parse with CourseEnum and it should be recipeCourse I presume. 我可以在您的代码中看到您将Enum.Parse与CourseEnum Enum.Parse使用,它应该是我认为的recipeCourse

I can't spot any place in your sample code where4 CourseEnum is defined. 我看不出在你的示例代码where4任何地方CourseEnum定义。

A @Hans Kesting said, the answer was here: Why can not reference a type through an expression? @Hans Kesting说,答案在这里: 为什么不能通过表达式引用类型?

The problem was using a field that has an enum type with the enum type itself. 问题是使用的字段本身具有枚举类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM