lundi 17 septembre 2018

Enforcer Description Attribute on C# Enums

Is there any way to enforce the usage of DescriptionAttribute on an Enum constants ?

I've tried creating a custom Attribute

    [DescriptionEnforcerAttribute("test")]
    public enum CachedKeys : int
    {
        Summer = 1,
        Winter = 2
    }

    [AttributeUsage(AttributeTargets.Enum)]
    public class DescriptionEnforcerAttribute : Attribute
    {
        public DescriptionEnforcerAttribute(string test)
        {
            CheckEnumConstantsForDescription();
        }

        private static IEnumerable<Type> GetMarkedTypes(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (type.GetCustomAttributes(typeof(DescriptionEnforcerAttribute), true).Length > 0)
                {
                    yield return type;
                }
            }
        }

        /// <summary>
        /// Checks if all constants from an enum have DescriptionAttribute
        /// </summary>
        private static void CheckEnumConstantsForDescription()
        {
            foreach (Type type in GetMarkedTypes(typeof(DescriptionEnforcerAttribute).Assembly))
            {
                MemberInfo[] members = type.GetType().GetMembers();

                foreach (MemberInfo member in members)
                {
                    if (member.GetCustomAttribute<DescriptionAttribute>() == null) throw new EnumDescriptionException();
                }
            }
        }

So the idea is that I want to create an Attribute that will check for all constants within an enum. It should throw an exception if it finds that there are constants that don't have the DescriptionAttribute marker.

Thanks





Aucun commentaire:

Enregistrer un commentaire