Convert.ChangeType and converting to enums?

前端 未结 3 1520
臣服心动
臣服心动 2020-12-10 09:54

I got an Int16 value, from the database, and need to convert this to an enum type. This is unfortunately done in a layer of the code that knows very little abou

3条回答
  •  无人及你
    2020-12-10 10:47

    Enum.ToObject(.... is what you're looking for!

    C#

    StringComparison enumValue = (StringComparison)Enum.ToObject(typeof(StringComparison), 5);
    

    VB.NET

    Dim enumValue As StringComparison = CType([Enum].ToObject(GetType(StringComparison), 5), StringComparison)
    

    If you do a lot of Enum converting try using the following class it will save you alot of code.

    public class Enum where EnumType : struct, IConvertible
    {
    
        /// 
        /// Retrieves an array of the values of the constants in a specified enumeration.
        /// 
        /// 
        /// 
        public static EnumType[] GetValues()
        {
            return (EnumType[])Enum.GetValues(typeof(EnumType));
        }
    
        /// 
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
        /// 
        /// 
        /// 
        /// 
        public static EnumType Parse(string name)
        {
            return (EnumType)Enum.Parse(typeof(EnumType), name);
        }
    
        /// 
        /// Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
        /// 
        /// 
        /// 
        /// 
        /// 
        public static EnumType Parse(string name, bool ignoreCase)
        {
            return (EnumType)Enum.Parse(typeof(EnumType), name, ignoreCase);
        }
    
        /// 
        /// Converts the specified object with an integer value to an enumeration member.
        /// 
        /// 
        /// 
        /// 
        public static EnumType ToObject(object value)
        {
            return (EnumType)Enum.ToObject(typeof(EnumType), value);
        }
    }
    

    Now instead of writing (StringComparison)Enum.ToObject(typeof(StringComparison), 5); you can simply write Enum.ToObject(5);.

提交回复
热议问题