C # TypeConverter long to enum type doesn't work in ChangeType

I am new to C # and .NET. I am trying to convert work from integer to enum. The conversion should be done using ChangeType (outside of my demo below this is fixed as within the framework of the data binding framework) and from what I read it should work with what I do, but I get an exception and if I put breakpoints in the functions of my transform class, nothing is called.

Thanks in advance! Matthew.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace csharptest
{
    class Program
    {

        [TypeConverter(typeof(UnitEnumConverter))]
        public enum LengthUnits
        {
            METRES,
            FEET
        };

        public class UnitEnumConverter : EnumConverter
        {
            public UnitEnumConverter(System.Type type)
                : base(type.GetType())
            {
            }

            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            {
                if (sourceType == typeof(Int64)) return true;

                return base.CanConvertFrom(context, sourceType);
            }

            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            {
                if (value is Int64)
                {
                    return (LengthUnits)(Int64)value;
                }
                return base.ConvertFrom(context, culture, value);
            }
        }

        static void Main(string[] args)
        {
            LengthUnits units = new LengthUnits();

            long x = 1;

            units = (LengthUnits)System.Convert.ChangeType(x, typeof(LengthUnits));

        }
    }
}

      

+2


source to share


1 answer


Since previous answers

Convert.ChangeType won't look at TypeConverter, so it won't help. Using Reflector to view Convert.ChangeType it just looks like it won't work. It has a static map of what it can convert to. If it's not on this list, it won't try to convert. This is ridiculous because straight int or long for your enum will work.



I'm not sure what binding framework you are using, but it seems odd that it would go that route for enums.

Sorry, I couldn't help more.

+3


source







All Articles