public static ListItemCollection BuildListFromEnum(Enum objEnum)
        {
            ListItemCollection colListItems = new ListItemCollection();
            ListItem liItem;

            SortedList colSortedListItems = new SortedList();

            foreach (int value in Enum.GetValues(objEnum.GetType()))
            {
                liItem = new ListItem();

                liItem.Value = value.ToString();
                liItem.Text = StringEnum.GetStringValue((Enum)Enum.Parse(objEnum.GetType(), value.ToString(), true));

                if (liItem.Text != string.Empty)
                {
                    colSortedListItems.Add(liItem.Text, liItem);
                }
                liItem = null;
            }

            foreach (ListItem liListItem in colSortedListItems.GetValueList())
            {
                colListItems.Add(liListItem);
            }

            return colListItems;
        }
Example #2
0
    public static System.Enum EnumPopup(Rect rect, string label, System.Enum enumerator, string[] minus)
    {
        System.Array  optionsEnums        = System.Enum.GetValues(enumerator.GetType());
        string[]      options             = System.Enum.GetNames(enumerator.GetType());
        string        selectedName        = System.Enum.GetName(enumerator.GetType(), enumerator);
        List <string> OriginalListOptions = ArrayUtility.ArrayToList(options);
        List <string> FilteredListOptions = ArrayUtility.ArrayToList(options);

        for (int i = 0; i < minus.Length; i++)
        {
            if (FilteredListOptions.Contains(minus[i]))
            {
                FilteredListOptions.Remove(minus[i]);
            }
        }
        int selectedIndex = FilteredListOptions.IndexOf(selectedName);

        selectedIndex = EditorGUI.Popup(rect, label, selectedIndex, FilteredListOptions.ToArray());
        if (selectedIndex < 0)
        {
            selectedIndex = 0;
        }
        selectedName = FilteredListOptions[selectedIndex];
        int nonfilteredSelectedIndex = OriginalListOptions.IndexOf(selectedName);

        return((System.Enum)(optionsEnums.GetValue(nonfilteredSelectedIndex)));
    }
Example #3
0
    public static List <System.Enum> GetFlagValues(this System.Enum enumFlags)
    {
        List <System.Enum> flagValues = new List <System.Enum>();
        long flagsNumber = System.Convert.ToInt64(enumFlags);

        if (Math.IsPowerOfTwo(flagsNumber))
        {
            flagValues.Add((System.Enum)System.Enum.ToObject(enumFlags.GetType(), flagsNumber));
            return(flagValues);
        }

        int bits = (int)System.Math.Ceiling(System.Math.Log(flagsNumber, 2));

        for (int i = 0; i <= bits; i++)
        {
            long bitValue = 1L << i;
            if ((flagsNumber & bitValue) == 0L)
            {
                continue;
            }

            flagValues.Add((System.Enum)System.Enum.ToObject(enumFlags.GetType(), bitValue));
        }

        return(flagValues);
    }
Example #4
0
        private static Attribute GetAttribute(Type t, Enum e)
        {
            var name = Enum.GetName(e.GetType(), e);
            var fieldInfo = e.GetType().GetField(name);

            return Attribute.GetCustomAttribute(fieldInfo, t);
        }
 /// <summary>
 /// Retrieves the message format from the DefaultMessage attribute decorating the
 /// message code
 /// </summary>
 /// <param name="code"></param>
 /// <returns></returns>
 protected string GetMessageFormat(Enum code)
 {
     System.Reflection.FieldInfo fi = code.GetType().GetField(code.ToString());
     var attributes = (DefaultMessageAttribute[])fi.GetCustomAttributes(typeof(DefaultMessageAttribute), false);
     return (attributes.Length > 0)
         ? attributes[0].Message
         : code.GetType().DeclaringType.FullName + "." + code.ToString();
 }
Example #6
0
 public static bool AnyFlag(this Enum baseEnum, Enum value)
 {
     if (!baseEnum.GetType().IsEquivalentTo(value.GetType()))
     {
         throw ExceptionHelper.EnumTypeDoesNotMatch(value.GetType(), baseEnum.GetType());
     }
     return ((ToUInt64(baseEnum) & ToUInt64(value)) != 0);
 }
        private void EvaluateEnum( Enum e )
        {
            Console.WriteLine( "Name: " + e.GetType().Name );
             Console.WriteLine( "Underlying Type: " + Enum.GetUnderlyingType( e.GetType() ) );
             Array values = Enum.GetValues(e.GetType());

             for (int i = 0; i < values.Length; i++)
            Console.WriteLine("Name: {0}, Value:{0:D}", values.GetValue(i));
        }
        static void CheckEnumHasFlagAttribute(Enum actual)
        {
#if NewReflection
            if (!actual.GetType().GetTypeInfo().IsDefined(typeof(FlagsAttribute), false))
#else
            if (!actual.GetType().IsDefined(typeof(FlagsAttribute), false))
#endif
            {
                throw new ArgumentException("Enum doesn't have Flags attribute", nameof(actual));
            }
        }
        public EnumDialog(Enum input)
        {
            this.InitializeComponent();
            this._enumType = input.GetType();

            foreach (var name in Enum.GetNames(input.GetType()))
            {
                this.comboBox1.Items.Add(name);
            }
            this.comboBox1.Text = input.ToString();
        }
Example #10
0
 private static void EvaluateEnum(Enum e)
 {
     Console.WriteLine(String.Format("Information about {0}", e.GetType().Name));
     Console.WriteLine(String.Format("Underlying type: {0}", e.GetTypeCode()));
     var enumData = Enum.GetValues(e.GetType());
     foreach (var item in enumData)
     {
         Console.WriteLine(String.Format("Name: {0}   Value: {0:d} ", item));
     }
     Console.WriteLine();
 }
Example #11
0
 public static bool EnumTryParse(string value, ref System.Enum e)
 {
     foreach (string name in System.Enum.GetNames(e.GetType()))
     {
         if (name == value)
         {
             e = (System.Enum)System.Enum.Parse(e.GetType(), value);
             return(true);
         }
     }
     return(false);
 }
Example #12
0
        static void EvaluateEnum(Enum e)
        {
            Console.WriteLine("=> Information about {0}", e.GetType().Name);
            Console.WriteLine("Underlying storage type: {0}", Enum.GetUnderlyingType(e.GetType()));

            Array enumData = Enum.GetValues(e.GetType());
            //var x =  enumData[0];
          
            Console.WriteLine("This enum has {0} members", enumData.Length);
            for(int i = 0; i < enumData.Length; i++)
            {
                Console.WriteLine("Name: {0}, Value {0:D}", enumData.GetValue(i));
            }
            Console.WriteLine();
        }
Example #13
0
 private static IList<byte> BytesFromPspIso( Stream iso, Enum file, int offset, int size )
 {
     if ( file.GetType() == typeof( FFTPack.Files ) )
     {
         return FFTPack.GetFileFromIso( iso, pspIsoInfo, (FFTPack.Files)file ).Sub( offset, offset + size - 1 );
     }
     else if ( file.GetType() == typeof( PatcherLib.Iso.PspIso.Sectors ) )
     {
         return PatcherLib.Iso.PspIso.GetFile( iso, pspIsoInfo, (PatcherLib.Iso.PspIso.Sectors)file, offset, size );
     }
     else
     {
         throw new ArgumentException();
     }
 }
Example #14
0
 /// <summary>
 /// ��ȡö��DescriptionAttribute ֵ
 /// </summary>
 /// <param name="eEnum"></param>
 /// <returns></returns>
 public static string GetDescription(Enum eEnum)
 {
     Type enumType = eEnum.GetType();
     FieldInfo fi = enumType.GetField(Enum.GetName(enumType, eEnum));
     DescriptionAttribute dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
     return dna == null ? string.Empty : dna.Description;
 }
Example #15
0
        public static string GetEnumRemark(Enum value)
        {
            Type type = value.GetType();
            string cacheKey = string.Format("{0}_Remark_{1}", type.Name, value);
            if (_cache.ContainsKey(cacheKey))
                return _cache[cacheKey];
            else
            {
                FieldInfo fieldInfo = type.GetField(value.ToString());

                string remark = string.Empty;
                try
                {
                    object[] attrs = fieldInfo.GetCustomAttributes(typeof(RemarkAttribute), false);

                    foreach (RemarkAttribute attr in attrs)
                    {
                        remark = attr.Remark;
                    }

                    if (!string.IsNullOrEmpty(remark))
                        _cache.SafeAdd(cacheKey, remark);
                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }

                return remark;
            }
        }
Example #16
0
        public static string EnumToString(Enum enumValue)
        {
            StringBuilder enumValueAsString = new StringBuilder();
            Type enumType = enumValue.GetType();
            string[] enumToStringParts = enumValue.ToString().Split(ENUM_FLAGGED_VALUE_SEPERATOR_CHARACTER);
            foreach (string enumValueStringPart in enumToStringParts)
            {
                FieldInfo enumValueField = enumType.GetField(enumValueStringPart.Trim());
                EnumValueDescriptionAttribute[] enumDesc = enumValueField.GetCustomAttributes(typeof(EnumValueDescriptionAttribute), false) as
                EnumValueDescriptionAttribute[];
                if (enumValueAsString.Length > 0)
                {
                    enumValueAsString.Append(ENUM_FLAGGED_VALUE_SEPERATOR_CHARACTER);
                }
                if (enumDesc.Length == 1)
                {
                    enumValueAsString.Append(enumDesc[0].Description);
                }
                else
                {
                    enumValueAsString.Append(enumValueStringPart);
                }

            }
            return enumValueAsString.ToString();
        }
Example #17
0
        /// <summary>
        /// Gets a string value for a particular enum value.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <returns>String Value associated via a <see cref="DescriptionAttribute"/> attribute, or null if not found.</returns>
        public static string GetStringValue(Enum value)
        {
            string output = null;
            var type = value.GetType();

            if (StringValues.ContainsKey(value))
                output = ((DescriptionAttribute)StringValues[value]).Description;
            else
            {
                var fi = type.GetField(value.ToString());
                var attrs = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
                // ReSharper disable PossibleNullReferenceException
                if (attrs.Length > 0)
                {
                    // ReSharper restore PossibleNullReferenceException
                    if (!StringValues.Contains(value))
                    {
                        StringValues.Add(value, attrs[0]);
                    }
                    output = attrs[0].Description;
                }

            }
            return output;
        }
Example #18
0
        /// <summary>
        /// Check to see if a flags enumeration has a specific flag set.
        /// </summary>
        /// <param name="variable">Flags enumeration to check</param>
        /// <param name="value">Flag to check for</param>
        /// <returns></returns>
        public static bool HasFlag(this Enum variable, Enum value)
        {
            if (variable == null)
            {
                return false;
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Not as good as the .NET 4 version of this function, but should be good enough

            if (!Enum.IsDefined(variable.GetType(), value))
            {
                throw new ArgumentException(string.Format(
                    "Enumeration type mismatch.  The flag is of type '{0}', was expecting '{1}'.",
                    value.GetType(), variable.GetType()));
            }

            ulong num = Convert.ToUInt64(value);

            return ((Convert.ToUInt64(variable) & num) == num);
        }
Example #19
0
        public static void Parse(string value, bool ignoreCase, Enum expected)
        {
            SimpleEnum result;
            if (!ignoreCase)
            {
                Assert.True(Enum.TryParse(value, out result));
                Assert.Equal(expected, result);

                Assert.Equal(expected, Enum.Parse(expected.GetType(), value));
            }

            Assert.True(Enum.TryParse(value, ignoreCase, out result));
            Assert.Equal(expected, result);

            Assert.Equal(expected, Enum.Parse(expected.GetType(), value, ignoreCase));
        }
        /// <summary>
        /// 列挙体に設定された文字列を取得する
        /// </summary>
        /// <param name="value">文字列が付加された列挙子</param>
        /// <returns>設定された文字列</returns>
        public static string GetStringValue(Enum value)
        {
            if (value == null) return null;

            // すでにキャッシュしたものがあればそれを返す
            if (m_Cashe.ContainsKey(value))
            {
                return m_Cashe[value];
            }

            // キャッシュになければ新しく取得
            Type enumType = value.GetType();
            string name = Enum.GetName(enumType, value);
            StringEnumAttribute[] attributes =
                (StringEnumAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(StringEnumAttribute), false);
            if (attributes.Length > 0)
            {
                // 属性があれば取得する
                string stringValue = attributes[0].m_StringValue;

                // キャッシュとして保存しておく
                m_Cashe[value] = stringValue;
                return stringValue;
            }
            else
            {
                // 属性がなければ無ければ空の値をキャッシュに保存してから返す
                // キャッシュとして保存しておく
                m_Cashe[value] = NoDataValue;
                return NoDataValue;
            }
        }
Example #21
0
        public static string GetStringValue(Enum value)
        {
            string output;
            var type = value.GetType();

            if (StringValues.ContainsKey(value))
            {
                output = StringValues[value].Value;
            }
            else
            {
                var fi = type.GetField(value.ToString());
                var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false)
                    as StringValueAttribute[];
                if (attrs != null && attrs.Length > 0)
                {
                    output = attrs[0].Value;
                    // Put it in the cache.
                    lock(StringValues)
                    {
                        // Double check
                        if (!StringValues.ContainsKey(value))
                        {
                            StringValues.Add(value, attrs[0]);
                        }
                    }
                }
                else
                {
                    return value.ToString();
                }
            }

            return output;
        }
Example #22
0
 internal static string EnumToTranslation(this ResourceManager r, Enum value)
 {
     var type = value.GetType();
     var name = Enum.GetName(type, value);
     var key = type.Name + name;
     return r.GetString(key) ?? "Key: " + key;
 }
 public override void SelectConcept(Enum concept)
 {
     base.SelectConcept(concept);
     if(concept.GetType().Equals(typeof(DataAccessConceptsList)))
     {
         switch((DataAccessConceptsList)concept)
         {
             case DataAccessConceptsList.WorkingWithFilesExamples:
                 conceptExecutionClass = new WorkingWithFilesExamples();
                 break;
             case DataAccessConceptsList.WorkingWithStreams:
                 conceptExecutionClass = new WorkingWithStreams();
                 break;
             case DataAccessConceptsList.WorkingWithADO_DOTNET_Concepts:
                 conceptExecutionClass = new WorkingWithADO_DOTNET_Concepts();
                 break;
             case DataAccessConceptsList.WorkingWithXMLConcepts:
                 conceptExecutionClass = new WorkingWithXMLExamples();
                 break;
             case DataAccessConceptsList.LINQExamples:
                 conceptExecutionClass = new LINQExamples();
                 break;
             case DataAccessConceptsList.SerializationAndDeserializationExamples:
                 conceptExecutionClass = new SerializationAndDeserializationExamples();
                 break;
             case DataAccessConceptsList.ImplementingClassHierarchy:
                 conceptExecutionClass = new ClassHierarchyExample();
                 break;
         }
     }
 }
Example #24
0
        /// <summary>
        /// Retrieve the description on the enum, e.g.
        /// [Description("Bright Pink")]
        /// BrightPink = 2,
        /// Then when you pass in the enum, it will retrieve the description
        /// </summary>
        /// <param name="en">The Enumeration</param>
        /// <returns>A string representing the friendly name</returns>
        public static EnumDescription GetDescription(Enum en)
        {
            Type type = en.GetType();

            string description = string.Empty;

            EnumDescription enumDescription = new EnumDescription()
            {
                EnumValue = en,
                EnumMemberName = en.ToString()
            };

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            description = en.ToString();

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    description = ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            enumDescription.Description = description;

            return enumDescription;
        }
        public static string GetStringValue(Enum value)
        {
            // Get the enum Type.
            var type = value.GetType();

            // Check if the enum already exits in the Dictionary.
            if (StringValues.ContainsKey(value))
                return StringValues[value].Value;

            // Get the enum field info.
            FieldInfo fi = type.GetField(value.ToString());

            // Convert the enums to the strings.
            EnumToStringAttribute[] attrs = fi.GetCustomAttributes(typeof(EnumToStringAttribute), false) as EnumToStringAttribute[];

            // if the attributes are null or if the length of the array is equal to 0 or 0, return null.
            if (attrs != null && attrs.Length <= 0)
                return null;
            if (attrs == null)
                return null;

            // add the enum to the Dictionary.
            StringValues.Add(value, attrs[0]);

            // Return the string.
            return attrs[0].Value;
        }
Example #26
0
        public static string GetEnumDescription(Enum enumValue)
        {
            FieldInfo fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
            List<DescriptionAttribute> attributes = fieldInfo.GetCustomAttributes<DescriptionAttribute>(false).ToList();

            return attributes.Count > 0 ? attributes[0].Description : enumValue.ToString();
        }
Example #27
0
        public static string GetStringValue(Enum value)
        {
            string output = null;
            Type type = value.GetType();

            //Check first in our cached results...
            if (_stringValues.ContainsKey(value))
                output = (_stringValues[value] as StringValueAttribute).Value;
            else
            {
                //Look for our 'StringValueAttribute' 
                //in the field's custom attributes
                FieldInfo fi = type.GetField(value.ToString());
                StringValueAttribute[] attrs =
                   fi.GetCustomAttributes(typeof(StringValueAttribute),
                                           false) as StringValueAttribute[];
                if (attrs.Length > 0)
                {
                    _stringValues.Add(value, attrs[0]);
                    output = attrs[0].Value;
                }
            }

            return output;
        }
Example #28
0
 /// <summary>
 /// Gets Enum Value's Description Attribute
 /// </summary>
 /// <param name="value">The value you want the description attribute for</param>
 /// <returns>The description, if any, else it's .ToString()</returns>
 public static string GetEnumDescription(Enum value) {
     FieldInfo fi = value.GetType().GetField(value.ToString());
     var attributes =
         (DescriptionAttribute[])fi.GetCustomAttributes(
                                      typeof(DescriptionAttribute), false);
     return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
 }
			public bool Equals (Enum e)
			{
				if (e == null)
					return false;
				else
					return e.GetType () == typeof (Days);
			}
 public static string ToDescription(Enum value)
 {
     var attributes =
         (DescriptionAttribute[])
         value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
     return attributes.Length > 0 ? attributes[0].Description : value.ToString();
 }
        private static string GetEnumDescription(Enum value)
        {
            if (value == null) return null;

            var type = value.GetType().GetTypeInfo();
            var res = value.ToString();

            if (type.CustomAttributes.Any(t => t.AttributeType == typeof(FlagsAttribute)))
            {
                var members = type.AsType().GetMembers();
                var conversion = members.SelectMany(t => t.GetCustomAttributes(typeof(DescriptionAttribute), false).Select(a => new KeyValuePair<string, string>(t.Name, ((DescriptionAttribute)a).Description))).ToDictionary(t => t.Key, t => t.Value);

                res = string.Join(",", res.Split(',').Select(t => t.Trim()).Select(t => conversion.ContainsKey(t) ? conversion[t] : t));
            }
            else
            {
                var memInfo = type.AsType().GetMember(value.ToString());

                if (memInfo.Length > 0)
                {
                    var attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false).ToList();

                    if (attrs.Any())
                        res = ((DescriptionAttribute)attrs.First()).Description;
                }
            }

            return res;
        }
 private static TAttribute GetAttribute <TAttribute>(this Enum enumValue) where TAttribute : Attribute
 {
     return(enumValue?.GetType()
            .GetMember(enumValue.ToString())
            .First()
            .GetCustomAttribute <TAttribute>());
 }
Example #33
0
		/// <summary>
		/// Enumeration valued field.
		/// </summary>
		/// <param name="Node">Node</param>
		/// <param name="FieldName">Name of field</param>
		/// <param name="StringIds">Corresponding String IDs</param>
		/// <param name="Timepoint">Timepoint of field value.</param>
		/// <param name="Value">Value</param>
		/// <param name="Type">Type of value.</param>
		public FieldEnum(string NodeId, string FieldName, FieldLanguageStep[] StringIds, DateTime Timepoint,
			Enum Value, ReadoutType Type)
			: base(NodeId, FieldName, StringIds, Timepoint, Type)
		{
			this.value = Value.ToString();
			this.dataType = Value.GetType ().FullName;
		}
Example #34
0
    public static T GetAttribute <T>(this System.Enum e) where T : System.Attribute
    {
        System.Type type      = e.GetType();
        FieldInfo   fieldInfo = type.GetField(System.Enum.GetName(type, e));

        return(fieldInfo.GetCustomAttribute <T>());
    }
Example #35
0
File: Masks.cs Project: srndpty/VFW
 public int BunnyMask(GUIContent content, Enum enumValue)
 {
     var enumType = enumValue.GetType();
     var enumNames = Enum.GetNames(enumType);
     var enumValues = Enum.GetValues(enumType) as int[];
     return BunnyMask(content, Convert.ToInt32(enumValue), enumValues, enumNames);
 }
Example #36
0
        /// <summary>
        /// An object extension method that gets description attribute.
        /// </summary>
        /// <param name="value">The value to act on.</param>
        /// <returns>The description attribute.</returns>
        public static string?GetDescription(this Enum value)
        {
            var attr = value?.GetType()
                       ?.GetField(value.ToString())
                       ?.GetCustomAttribute <DescriptionAttribute>();

            return(attr?.Description);
        }
Example #37
0
    public void RenderDynamicEnum(string Label, System.Enum Enum, ref string Val)
    {
        List <string> Names = System.Enum.GetNames(Enum.GetType()).ToList();

        if (!Names.Contains(Val) && Names.Count > 0)
        {
            Val = Names [0];
        }

        var Value = (System.Enum)System.Enum.Parse(Enum.GetType(), Val);

        Value = EditorGUILayout.EnumPopup(Label, Value);

        var ParseValue = System.Enum.Parse(Value.GetType(), Value.ToString());

        Val = (string)ParseValue.ToString();
    }
    //---------------------------------------
    // IGUIHelper interface stuff:
    //---------------------------------------
    public System.Enum EnumField(string label, System.Enum selected)
    {
#if UNITY_IPHONE && !(UNITY_3_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 || UNITY_3_6 || UNITY_3_7 || UNITY_3_8 || UNITY_3_9)
        GUILayout.Label(label);
        return((System.Enum)System.Enum.ToObject(selected.GetType(), EditorGUILayout.Popup((int)selected, System.Enum.GetNames(selected.GetType()), GUILayout.Width(150f))));
#else
        return(EditorGUILayout.EnumPopup(label, selected, GUILayout.Width(220f)));
#endif
    }
Example #39
0
    public void RenderDynamicEnum(string Label, System.Enum Enum, ref int Index)
    {
        string[] Names = System.Enum.GetNames(Enum.GetType());

        if (Names.Length > 0)
        {
            var Val = (System.Enum)System.Enum.Parse(Enum.GetType(), Names [0]);
            if (Names.Length > Index && Names.Length > 0)
            {
                Val = (System.Enum)System.Enum.Parse(Enum.GetType(), Names [Index]);
            }

            Val = EditorGUILayout.EnumPopup(Label, Val);

            // to int again
            var value = System.Enum.Parse(Val.GetType(), Val.ToString());
            Index = System.Convert.ToInt32(value);
        }
    }
Example #40
0
    public static string GetEnumDesc(System.Enum obj)
    {
        string objName = obj.ToString();

        System.Type t  = obj.GetType();
        FieldInfo   fi = t.GetField(objName);

        System.ComponentModel.DescriptionAttribute[] arrDesc = (System.ComponentModel.DescriptionAttribute[])fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
        return(arrDesc != null && arrDesc.Length > 0 ? arrDesc[0].Description : "");
    }
Example #41
0
    /// <summary>
    ///     An object extension method that gets description attribute.
    /// </summary>
    /// <param name="value">The value to act on.</param>
    /// <returns>The description attribute.</returns>
    public static string GetCustomAttributeDescription(this System.Enum value)
    {
        var attribute = value
                        .GetType()
                        .GetField(value.ToString())
                        .GetCustomAttributes(typeof(DescriptionAttribute), false)
                        .FirstOrDefault() as DescriptionAttribute;

        return(attribute?.Description);
    }
Example #42
0
        // This method will print out the details of any enum.
        static void EvaluateEnum(System.Enum e)
        {
            Console.WriteLine("=> Information about {0}", e.GetType().Name);

            Console.WriteLine("Underlying storage type: {0}",
                              Enum.GetUnderlyingType(e.GetType()));

            // Get all name/value pairs for incoming parameter.
            Array enumData = Enum.GetValues(e.GetType());

            Console.WriteLine("This enum has {0} members.", enumData.Length);

            // Now show the string name and associated value.
            for (int i = 0; i < enumData.Length; i++)
            {
                Console.WriteLine("Name: {0}, Value: {1:D}",
                                  enumData.GetValue(i), enumData.GetValue(i));
            }
            Console.WriteLine();
        }
Example #43
0
        /// <summary>
        /// 获取枚举值
        /// </summary>
        /// <param name="instance">枚举实例</param>
        public static int Value(this System.Enum instance)
        {
            Type   type  = instance.GetType();
            string value = instance.SafeString();

            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentNullException(nameof(instance));
            }
            return((int)System.Enum.Parse(type, instance.ToString(), true));
        }
Example #44
0
        public static string GetDescription(this System.Enum e)
        {
            var fi         = e.GetType().GetField(e.ToString());
            var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return(attributes[0].Description);
            }
            return(e.ToString());
        }
Example #45
0
    /// <summary>
    /// A convenience method to reduce the hassle of obtaining the
    /// attribute instance associated with an enum value.
    /// </summary>
    /// <typeparam name="TAttribute">An attribute type</typeparam>
    /// <param name="value">The enum value </param>
    /// <returns>The <typeparamref name="TAttribute"/>instance associated
    /// with the <paramref name="value"/> or null if no attribute exists</returns>
    public static TAttribute GetAttribute <TAttribute>(this System.Enum value)
        where TAttribute : System.Attribute
    {
        var type = value.GetType();
        var name = System.Enum.GetName(type, value);

        return(type.GetField(name) // I prefer to get attributes this way
               .GetCustomAttributes(false)
               .OfType <TAttribute>()
               .SingleOrDefault());
    }
Example #46
0
        public static string GetCode(this System.Enum value)
        {
            var typeInfo   = value.GetType();
            var attributes = typeInfo.GetCustomAttributes(typeof(CodeAttribute), false).Cast <CodeAttribute>().ToArray();

            if ((attributes?.Count() ?? 0) <= 0)
            {
                return(null);
            }
            return(attributes[0].Code);
        }
Example #47
0
        private static void EvaluateEnum(System.Enum e)
        {
            ConsoleColor prevColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("=> Information about {0}", e.GetType().Name);
            Console.WriteLine("Underlying storage type: {0}", Enum.GetUnderlyingType(e.GetType()));
            // Get all name/value pairs for incoming parameter.
            Array enumData = Enum.GetValues(e.GetType());

            Console.WriteLine("This enum has {0} members.", enumData.Length);
            // Now show the string anme and associated value, using the D format
            // flag (see Chapter3).
            for (int i = 0; i < enumData.Length; i++)
            {
                Console.WriteLine("Name: {0}, Value: {0:D}", enumData.GetValue(i));
            }
            Console.ForegroundColor = prevColor;
            Console.WriteLine();
        }
        /// <summary>
        /// 获得枚举字段的特性(Attribute),该属性不允许多次定义。
        /// </summary>
        public static string GetAttributeValue(System.Enum thisValue)
        {
            FieldInfo field = thisValue.GetType().GetField(thisValue.ToString());
            var       attr  = (Attribute.GetCustomAttribute(field, typeof(EnumAttributeDesc)) as EnumAttributeDesc);

            if (attr == null)
            {
                return(string.Empty);
            }
            return((Attribute.GetCustomAttribute(field, typeof(EnumAttributeDesc)) as EnumAttributeDesc).Value);
        }
Example #49
0
        public static string GetEnumDescription(System.Enum value)
        {
            var fi = value.GetType().GetField(value.ToString());

            var attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                    typeof(DescriptionAttribute),
                    false);

            return(attributes.Length > 0 ? attributes[0].Description : value.ToString());
        }
Example #50
0
        private static void Debug_ValidateMask(System.Enum value, uint mask)
        {
            Type t       = value.GetType();
            uint newmask = 0;

            foreach (int iVal in Enum.GetValues(t))
            {
                newmask = newmask | (uint)iVal;
            }
            System.Diagnostics.Debug.Assert(newmask == mask, "Mask not valid in IsEnumValid!");
        }
Example #51
0
        public static List <OrderedPair <int, string> > GetNameValuePairs(this System.Enum enumToUse)
        {
            var typeOfEnum            = enumToUse.GetType();
            var orderedNameValuePairs = new List <OrderedPair <int, string> >();

            foreach (var value in System.Enum.GetValues(typeOfEnum))
            {
                orderedNameValuePairs.Add(new OrderedPair <int, string>(Convert.ToInt32(value),
                                                                        ((System.Enum)value).GetDescription()));
            }
            return(orderedNameValuePairs);
        }
Example #52
0
        public static string StringValueOf(System.Enum value)
        {
            FieldInfo fi         = value.GetType().GetField(value.ToString());
            var       attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return(attributes[0].Description);
            }

            return(value.ToString());
        }
Example #53
0
        /// <summary>
        /// 读取 <see cref="System.Enum"/> 标记 <see cref="System.ComponentModel.DescriptionAttribute"/> 的值
        /// </summary>
        /// <param name="value">原始 <see cref="System.Enum"/> 值</param>
        /// <returns></returns>
        public static string GetDescription(this System.Enum value)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            FieldInfo            fieldInfo = value.GetType().GetField(value.ToString());
            DescriptionAttribute attribute = fieldInfo.GetCustomAttribute <DescriptionAttribute> (false);

            return(attribute.Description);
        }
Example #54
0
        public static IEnumerable <System.Enum> EnumerateSettedUpFlags(this System.Enum flags)
        {
            foreach (var value in System.Enum.GetValues(flags.GetType()).Cast <System.Enum>())
            {
                var hasFlag = flags.HasFlag(value);

                if (hasFlag)
                {
                    yield return(value);
                }
            }
        }
Example #55
0
        /// <summary>
        /// 获得枚举的 value--->EnumDescription 对应字典
        /// </summary>
        /// <param name="enum"></param>
        /// <returns></returns>
        public static Dictionary <int, string> GetDesciptions(this System.Enum @enum)
        {
            Dictionary <int, string> result = new Dictionary <int, string>();

            string[] values = System.Enum.GetNames(@enum.GetType());
            if (values == null || values.Length <= 0)
            {
                return(result);
            }

            for (int i = 0; i < values.Length; i++)
            {
                result[i] = "";
            }
            foreach (string key in values)
            {
                int i = (int)System.Enum.Parse(@enum.GetType(), key);
                result[i] = GetDescription(System.Enum.Parse(@enum.GetType(), key).GetType());
            }
            return(result);
        }
Example #56
0
 public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues)
 {
     System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in.");
     for (int i = 0; i < enumValues.Length; i++)
     {
         if (enumValues[i] == value)
         {
             return(true);
         }
     }
     return(false);
 }
Example #57
0
 /// <summary>
 /// get enum description for specific enum
 /// </summary>
 /// <param name="enum"></param>
 /// <param name="enumname"></param>
 /// <returns></returns>
 public static string ToDescriptionString(this System.Enum @enum, string enumname)
 {
     try
     {
         var attribute = @enum.GetType().GetField(enumname).GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
         return(attribute == null? @enum.ToString() : ((DescriptionAttribute)attribute).Description);
     }
     catch
     {
         return(null);
     }
 }
Example #58
0
        /// <summary>
        /// 根据枚举类型和枚举值获取枚举描述
        /// </summary>
        /// <returns></returns>
        public static string ToDescription(this System.Enum value)
        {
            if (value == null)
            {
                return("");
            }

            Type   type     = value.GetType();
            string enumText = System.Enum.GetName(type, value);

            return(GetDescription(type, enumText));
        }
Example #59
0
        /// <summary>
        /// 将一个标记了 <see cref="FlagsAttribute "/> 特性的枚举值分解成其包含已合并的多个该类型的枚举值。
        /// 例如通过对枚举值 BindingFlags.GetField | BindingFlags.GetProperty 指定该方法,将会返回一个数组 { BindingFlags.GetField, BindingFlags.GetProperty }。
        /// 如果传入的枚举参数所属的枚举类型未标记 <see cref="FlagsAttribute "/> 特性,该方法将会抛出异常。
        /// 注意,传入的泛型参数 <typeparamref name="T"/> 必须与枚举值 <paramref name="_this"/> 的相同。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_this"></param>
        /// <returns></returns>
        public static T[] Decompose <T>(this System.Enum _this) where T : struct
        {
            Type thisType = _this.GetType();
            Type enumType = typeof(T);

            if (thisType != enumType)
            {
                throw new ArgumentException(string.Format("传入的枚举值 {0} 其类型为 {1},与被转换的目标类型 {2} 不一致。", _this, thisType, enumType));
            }

            return(Decompose(_this).Select(item => (T)(object)item).ToArray());
        }
Example #60
0
        public bool IsValid(T objectToValidate)
        {
            if (objectToValidate != null)
            {
                System.Enum enumToCheck = _enumToCheck(objectToValidate);
                Type        enumType    = enumToCheck.GetType();
                string      enumName    = System.Enum.GetName(enumType, enumToCheck);

                return(System.Enum.GetNames(enumType).Any(name => name == enumName));
            }
            return(false);
        }