C# Attributes mandatory property

前端 未结 3 1173
时光说笑
时光说笑 2021-01-14 03:00

I\'ve created attribute like

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute :          


        
相关标签:
3条回答
  • 2021-01-14 03:09

    The accepted answer by Jon Skeet is a good solution. However, you can write this with shorter code nowadays. It works the same:

    public class TestPropertyAttribute : Attribute
    {
        public TestPropertyAttribute(string name)
        {
            Name = name;
        }
    
        public string Name { get; }
    }
    
    0 讨论(0)
  • 2021-01-14 03:13

    Put it in the constructor instead of just as a separate property:

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    [Serializable]
    public class TestPropertyAttribute : System.Attribute
    {
        readonly string _name;
    
        public TestPropertyAttribute(string name)
        {
            _name = name;
        }
    
        public string Name { get { return _name; } }
    }
    

    I don't believe you can make it mandatory and use the Name=... syntax when applying the attribute though.

    0 讨论(0)
  • 2021-01-14 03:15

    You should use the System.ComponentModel.Data.Annotations.StringLength (dot.NET 4) attribute to force the min length of the string, and validate in your Data. Also, (and people will mock me for this as it's bad design usually*) i would throw an InvalidDataException("You must enter a Name in the attribute") from the ctor when Name is not filled.

    The reason i would use this is because this is a design-time attribute and the exception would run as the app starts, so it would be easier to fix for the developer, this is not the best option, but I do not know how to communicate with the designer.

    I have been looking on ways to communicate directly with the warnings/error in the ErrorList, but until now i have not found an easy way to do this, beside building my own custom designer or addin. I have thought alot about builing an addin that would look for an SendWarning, SendError , custom attributes, but have yet to make it happen.

    as i said

     public sealed class TestPropertyAttribute : System.Attribute
    {
        [System.ComponentModel.DataAnnotations.StringLength(50),Required]
        public string Name
        {
            get { return _name; }
            set
      { 
             if (String.IsNullOrEmpty(value)) throw new InvalidDataException("Name is a madatory property,  please fill it out not as null or string.Empty thanks"); }
           else
          _name= value;
    
    
      }
           string _name;
     }
    
    0 讨论(0)
提交回复
热议问题