C# Attributes mandatory property

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

I\'ve created attribute like

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


        
3条回答
  •  一个人的身影
    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;
     }
    

提交回复
热议问题