我试图通过查看另一个对象中保存的字符串值来在自定义对象上设置自定义枚举属性,但我不断收到错误“无法通过表达式引用类型”。
到目前为止我已经尝试过
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;
}
}