Attributes and Named/Optional constructor parameters not working

前端 未结 3 1894
耶瑟儿~
耶瑟儿~ 2021-01-01 12:09

I have custom attribute defined like so:

  [AttributeUsage(AttributeTargets.Field)]
  public class EnumDisplayAttribute : Attribute
  {
    public string Des         


        
3条回答
  •  天涯浪人
    2021-01-01 12:33

    Optional parameters were added to C# after optional values for attributes already existed in C#. Therefore, for optional attribute parameters, you should fall back to the attribute-specific syntax:

    [AttributeUsage(AttributeTargets.Field)]
    public class EnumDisplayAttribute : Attribute
    {
        public string Description { get; set; }
        public string Code { get; set; }
    
        public EnumDisplayAttribute()
        {
        }
    }
    
    public enum TransactionType
    {
        [EnumDisplay(Code = "B")] 
        Bill,
        [EnumDisplay(Description = null, Code = "C")]
        CashReceipt,
    }
    

    As you see, the end-result is effectively the same, but instead of using named arguments, you are using named properties (where syntax like [EnumDisplay(Description = null, Code = "C")] is only possible in attribute declarations).

    Another way to think of it is that attribute declarations "borrowed" its syntax from method/constructor invocations, but attribute declarations are not in themselves method invocations, so they don't get all the same features as methods.

提交回复
热议问题