Attributes and Named/Optional constructor parameters not working

前端 未结 3 1897
耶瑟儿~
耶瑟儿~ 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:51

    If you do want to push values into your attribute using a constructor (e.g. if some of your attribute's properties are mandatory or to perform some kind of processing on them) you can always go old school and overload the constructor.

    For example:

    [AttributeUsage(AttributeTargets.Field)]
    public class SampleAttribute : Attribute
    {
        public string MandatoryProperty { get; private set; }
        public string OptionalProperty { get; private set; }
    
        // we use an overload here instead of optional parameters because 
        // C# does not currently support optional constructor parameters in attributes
        public SampleAttribute(string mandatoryProperty)
            : this(mandatoryProperty, null)
        {
        }
    
        public SampleAttribute(string mandatoryProperty, string optionalProperty)
        {
            MandatoryProperty = mandatoryProperty;
            OptionalProperty = optionalProperty;
        }
    }
    

提交回复
热议问题