Dynamic enum converter

女生的网名这么多〃 提交于 2019-12-08 12:25:17

问题


I want to create a dynamic 2-way-converter for all possible enums in my application.

I don't want to have to create a converter for each enum, I want to create one converter that provides converting from enum to byte and from byte to enum vice versa.

How can I get there? My approach is already 2-way but requires a static cast (MyEnum) in the code:

public class MyEnumConverter : MarkupExtension, IValueConverter 
        {
        public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture) {
            return (MyEnum)value;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, CultureInfo culture) {
            return (byte)value;
        }

        public override object ProvideValue(System.IServiceProvider serviceProvider) {
            return this;
        }
    }

回答1:


I believe you can do this 2 different ways.

Option 1: Take advantage of the targetType parameter on the convert methods. When you need to convert to the enum, then targetType is the enum type. You can use one of the static methods on the System.Enum class to do the conversion.

Option 2: In your xaml, use the ConverterParameter to pass in the enum type you want to convert to:

Converter={local:MyConverter, ConverterParameter={x:Type MyEnumType}}

If you go that route, then the type will be in the parameter parameter of the convert methods. Again, the static methods on the System.Enum class will do the heavy lifting for you.




回答2:


Try these extension methods, It will convert from enum to datatype(int, byte,..) and from datatype(int, byte,..) to enum vice versa..

    public static T ToEnumValue<T, E>(this E enumType)
    {
        return (T)Enum.ToObject(typeof(E), enumType);
    }

    public static E ToEnumType<T, E>(this T enumString)
    {
        return (E)Enum.Parse(typeof(E), enumString.ToString());
    }

Ex: To use the above methods, Take a enum

public enum EmployeeType
{
    Permanent = 0,
    Contract = 1,
}

int value = EmployeeType.Contract.ToEnumValue<int, EmployeeType>(); // 1
EmployeeType employeeType = value.ToEnumType<int, EmployeeType>();  // Contract


来源:https://stackoverflow.com/questions/13365384/dynamic-enum-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!