我有一个类,其属性如下:
[TypeConverter(typeof(SomeNameEnumValueConvert))]
public Example ExampleName { get; set; }在Enum TypeConverter中,我尝试从某个整数获取Enum名称,因为源是从一个由字符串组成的表中读取的。
在表中,它被存储为例如"33“(而不是名称),例如
public enum Example
{
Off = 1,
On = 33,
Whatever = 7
}下面是我的转换器代码:
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
var enumValue = Convert.ToInt32(value);
return (context.PropertyDescriptor.PropertyType) enumValue
}但是,它给出了上下文是一个变量,而不是类型的。因此,我尝试了各种方法使这个工作,但平行于此,我会张贴在这里,也许这加快了重试。我尝试过向Enum转换,通过(Enum)(对象),通过GetType进行强制转换,通过程序集进行强制转换,得到特定的类型,但这一切似乎都不起作用。因此,如何转换为基础系统类型。
发布于 2019-01-15 06:46:00
以获得枚举名称(例如:)从值中,您可以使用Enum.GetName
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var enumValue = Convert.ToInt32(value);
return Enum.GetName(context.PropertyDescriptor.PropertyType, enumValue);
}要从值中获取枚举成员(例如Example.On),请使用Enum.ToObject:
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var enumValue = Convert.ToInt32(value);
return Enum.ToObject(context.PropertyDescriptor.PropertyType, enumValue);
}发布于 2019-01-15 07:15:09
如果您想要一个通用的解决方案,可以尝试这样做:
public static class Example
{
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Foo()
{
Day day = Day.Tue;
int dayIndex = day.ToInt();
// dayIndex = 2
Day result = (dayIndex + 2).ToEnum<Day>();
// result = Thu
}
public static int ToInt<T>(this T t) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumeration type");
}
return Convert.ToInt32(t);
}
public static T ToEnum<T>(this int i) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumeration type");
}
return (T)Enum.ToObject(typeof(T), i);
}
}发布于 2019-01-15 06:23:45
在你的转换器里试试这个:
Example expEnum = (Example)Enum.Parse(typeof(Example), value.ToString(), true);
return expEnum;https://stackoverflow.com/questions/54193467
复制相似问题