Is it possible to add custom properties to c# enum object?

后端 未结 2 937
深忆病人
深忆病人 2021-01-22 20:16

Using c# Is it possible using to associate properties for each enum items?

I have used the Description Attribute to add English description to an enum item.

相关标签:
2条回答
  • You can decorate elements with custom Attributes. Those can contain nearly anything you want.

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class DescriptorAttribute : Attribute
    {
        public bool IsFirst { get; }
        public int UnitType { get; }
    
        public DescriptorAttribute(bool isFirst, int unitType)
        {
            IsFirst = isFirst;
            UnitType = unitType;
        }
    }
    

    You would use this as follows:

    public enum Test
    {
        [Descriptor(isFirst: true, unitType: 2)]
        Element
    }
    

    you already have the code to read this attribute in your question.

    0 讨论(0)
  • 2021-01-22 20:43

    You can create yet another extention method for this.

    public static object Create(this MyEnum enum)
    {
        switch (enum)
        {
             case MyEnum.First:
                  return new { IsFirst = true, UnitType = 1}];
             case MyEnum.Second:
                  return new ...
             default:
                  ...
        }
    }
    

    then use it like so:

    dynamic first = MyEnum.First.Create();
    var isFirst = first.IsFirst;
    

    but you really should consider creating a factory to create your objects.

    0 讨论(0)
提交回复
热议问题