Enum is how to use?

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

One, foreword

For the enumeration of Enum, we are very familiar with, but the enumeration appeared on the scene very much, is it right? We can abstract a general solution. The code you can write, but not everyone likes to write duplicate code, always use Ctrl+C and Ctrl+V tired not tired? A lot of people like me, really don't like to write duplicate code, code written in BUG is much more,. For the common scene, most people like abstracted, write a general, each place can use, and not easy to make mistakes. Of course, you like Ctrl+C and Ctrl+V, I also have no way....

Two, int value, string value is converted to Enum

As follows, a simple enumeration:

    public enum ExchangeType
    {
        [EnumFieldAttribute("Unlimited", true)] 
        All = 0,
        [EnumFieldAttribute("Shenzhen Stock Exchange")]
        SZSE = 1
    }

Enter the code for the following:

            ExchangeType type = (ExchangeType)3;

            if (type == ExchangeType.All)
            {
                Console.WriteLine("ExchangeType.All.");
            }
            else if (type == ExchangeType.SZSE)
            {
                Console.WriteLine("ExchangeType.SZSE.");
            }
            else
            {
                Console.WriteLine("Non Exist!");
            }

For the forced conversion, you can guess, what will be the output....

For the results, you can go to the test, and you may expect inconsistent values´╝ü

As for the following code:

ExchangeType type;
bool success = Enum.TryParse<ExchangeType>("3", out  type);

TryParse implementation of the results returned from success is successful (true), but the expectation is not necessarily correct.

Therefore, for the enumeration of conversion, or very easy to make a mistake. Therefore, must provide a default value to ensure the transformation fails, return the correct values. For the int value and string value is converted to Enum code.:

        public static T ToEnum<T>(int value, T defaultT) where T : struct
        {
            string enumName = Enum.GetName(typeof(T), value);

            return ToEnum<T>(enumName, defaultT);
        }

        public static T ToEnum<T>(string enumName, T defaultT) where T : struct
        {
            if (string.IsNullOrWhiteSpace(enumName))
            {
                return defaultT;
            }

            T result;

            if (!Enum.TryParse<T>(enumName.Trim(), out result))
            {
                return defaultT;
            }

            if (Enum.IsDefined(typeof(T), result))
            {
                return result;
            }

            return defaultT;
        }

In addition to the other application is also provided, as will a string that contains the ExchangeType.All type name prefix conversion Cheng Meiju, also need to provide default values to ensure the accuracy of conversion results, the code as follows:

        public static T TryParse<T>(string typeValue, T defaultValue, bool containsTypeName = false) where T : struct
        { 
            typeValue = (typeValue ?? string.Empty).Trim();

            if (containsTypeName)
            {
                int startIndex = typeValue.IndexOf(".");

                if (startIndex > 0 && typeValue.Length > startIndex + 1)
                {
                    typeValue = typeValue.Substring(startIndex + 1);
                }
            }

            return ToEnum<T>(typeValue, defaultValue);
        }

The application of words, relatively simple, ExchangeType type = EnumFieldProvider.TryParse<ExchangeType>("ExchangeType.", ExchangeType.All, true);

Three, advanced application of universal way

In the drop-down list, many scenes and enumeration, hard coding can also directly bind. But the enumeration many times is it right? Write a lot of code, but does not necessarily ensure correct code. If so, then write a generic, everyone relaxed:

        public static EnumFieldAttribute GetEnumAttribute(Type type)
        {
            if (type == null)
            {
                return null;
            }

            object[] customAttributes = type.GetCustomAttributes(typeof(EnumFieldAttribute), true);
            EnumFieldAttribute attribute = null;

            foreach (object attr in customAttributes)
            {
                attribute = attr as EnumFieldAttribute;

                if (attribute != null)
                {
                    return attribute;
                }
            }

            return null;
        }

        public static IList<EnumItem<T>> GetItems<T>(bool isSpecialRequired = false) where T : struct
        {
            var fields = typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public);

            if (fields == null || fields.Count() == 0)
            {
                return new List<EnumItem<T>>();
            }

            var enumItems = new List<EnumItem<T>>();
            EnumFieldAttribute attribute = null;
            T currentValue;

            foreach (var field in fields)
            {
                object[] customAttributes = field.GetCustomAttributes(typeof(EnumFieldAttribute), true);
                foreach (object attr in customAttributes)
                {
                    attribute = attr as EnumFieldAttribute;

                    if (attribute != null)
                    {
                        if (attribute.IsSpecialRequired)
                        {
                            if (!isSpecialRequired)
                            {
                                continue;
                            }
                        }

                        currentValue = (T)field.GetValue(null);

                        enumItems.Add(new EnumItem<T>(currentValue, attribute.Desc));
                    }
                } 
            }

            return enumItems;
        }

        public static IList<EnumItem<T>> GetItems<T>(IList<T> entities) where T : struct
        {
            if (entities == null || entities.Count() == 0)
            {
                return new List<EnumItem<T>>();
            }

            var enumItems = new List<EnumItem<T>>();

            foreach (var entity in entities)
            {
                enumItems.Add(GetItem<T>(entity));
            }

            return enumItems;
        }

        public static string GetItemDescription<T>(T enumItem) where T : struct
        {
            var field = typeof(T).GetField(enumItem.ToString());

            if (field == null)
            {
                return string.Empty; 
            }

            object[] customAttributes = field.GetCustomAttributes(typeof(EnumFieldAttribute), true);
            foreach (object attr in customAttributes)
            {
                EnumFieldAttribute attribute = attr as EnumFieldAttribute;

                if (attribute != null)
                {
                    return attribute.Desc;
                }
            }

            return string.Empty; 
        }

        public static EnumItem<T> GetItem<T>(T enumItem) where T : struct
        {
            var field = typeof(T).GetField(enumItem.ToString());

            if (field == null)
            {
                return new EnumItem<T>(enumItem, enumItem.ToString());
            }

            object[] customAttributes = field.GetCustomAttributes(typeof(EnumFieldAttribute), true);
            foreach (object attr in customAttributes)
            {
                EnumFieldAttribute attribute = attr as EnumFieldAttribute;

                if (attribute != null)
                {
return new EnumItem<T>(enumItem, attribute.Desc);
                }
            }

            return new EnumItem<T>(enumItem, enumItem.ToString());
        }

The method of public static IList<EnumItem<T>> GetItems<T>(bool isSpecialRequired = false) where T : struct, Provide a parameter to screen whether the parameter is required, Enumeration type ExchangeType are defined as above in   EnumFieldAttribute ("no limit", true), The EnumFieldAttribute ("no limit", true) second parameters and isSpecialRequired parameters.

Test code as follows:

        [TestMethod()]
        public void GetItemsTest()
        {
            IList<EnumItem<ExchangeType>> actual = EnumFieldProvider.GetItems<ExchangeType>(true);
            Assert.AreEqual(actual.Count, 2);
            Assert.AreEqual(actual[0].Value, ExchangeType.All);
            Assert.AreEqual(actual[1].Value, ExchangeType.SZSE);
        }

        [TestMethod()]
        public void GetItemsWithFalseArgTest()
        { 
            IList<EnumItem<ExchangeType>> actual = EnumFieldProvider.GetItems<ExchangeType>();
            Assert.AreEqual(actual.Count, 1);
            Assert.AreEqual(actual[0].Value, ExchangeType.SZSE);
        }

Returns the result can be used to the drop-down list, ListBox and other related control value bindings and display (because I have to work tomorrow, this paper does not provide, the essay provides).

Four, summary

For details, still need to spend time and effort to summarize. With much, naturally understand, wash bed...

Today is July 1st, it is a memorial day. 4 years ago, in June 26th graduated from the gala, brother started to work the first day is July 1st. Then, for the past 4 years, life is like a play...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Kennedy at November 16, 2013 - 8:47 PM