Should Convert Enum - CSharp System

CSharp examples for System:Enum

Description

Should Convert Enum

Demo Code


using System.Threading.Tasks;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Reflection.Emit;
using System.Reflection;
using System.Linq;
using System.IO;/*  w  w  w . j a  v  a  2s  . c o  m*/
using System.Globalization;
using System.Collections.Generic;
using System;

public class Main{
        public static bool ShouldConvertEnum(this MemberInfo member, Type enumType, out Type toType)
        {
            var attr = member.GetCustomAttribute<JilDirectiveAttribute>();
            if (attr == null || attr.TreatEnumerationAs == null)
            {
                toType = null;
                return false;
            }

            var primitiveType = Enum.GetUnderlyingType(enumType);
            var convert = attr.TreatEnumerationAs;

            bool underlyingSigned, targetSigned;
            int underlyingSize, targetSize;

            if (!GetEnumUnderlyingPrimitiveInfo(primitiveType, out underlyingSigned, out underlyingSize) || !GetEnumUnderlyingPrimitiveInfo(primitiveType, out targetSigned, out targetSize))
            {
                throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], convert is not an acceptable integer primitive type");
            }

            // possible cases
            // both are signed and target is equal or large to underlying => OK
            // underlying is unsigned, and target is unsigned and equal or larger => OK
            // underlying is unsigned and target is signed and larger => OK
            // underlying is signed, target is unsigned => NOPE
            // underlying is unsigned, target is signed and equal or smaller => NOPE

            if (underlyingSigned && !targetSigned)
            {
                throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], there is a signed/unsigned mismatch");
            }

            if (!underlyingSigned && (targetSigned && targetSize <= underlyingSize))
            {
                throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], target type is not large enough");
            }

            toType = convert;
            return true;
        }
        public static bool ShouldConvertEnum(this MemberInfo member, Type enumType)
        {
            Type ignored;
            return member.ShouldConvertEnum(enumType, out ignored);
        }
        public static Type GetUnderlyingType(this Type t)
        {
            return Nullable.GetUnderlyingType(t);
        }
}

Related Tutorials