What ways can I ensure that a string property is of a particular length?

前端 未结 5 1615
北海茫月
北海茫月 2020-12-18 17:31

I\'ve created some classes that will be used to provide data to stored procedures in my database. The varchar parameters in the stored procs have length specif

5条回答
  •  既然无缘
    2020-12-18 18:10

    Well, whatever way you go, what's executed is going to look like your second method. So the trick is getting your first method to act your second.

    First of all, It would need to be [MaxStringLength(50)]. Next, all that's doing is adding some data to the Type object for this class. You still need a way of putting that data to use.

    One way would be a binary re-writer. After compilation (but before execution), the rewriter would read the assembly, looking for that Attribute, and when finding it, add in the code for the check. The retail product PostSharp was designed to do exactly that type of thing.

    Alternately, you could trigger it at run-time. SOmething like:

    public class MyDataClass 
    { 
         private string _CompanyName;
    
         [MaxStringLength(50)] 
         public string CompanyName 
         { 
             get {return _CompanyName;} 
             set 
             { 
                 ProcessValidation()
                  _CompanyName = value; 
             } 
         } 
    }
    

    That's still quite ugly, but it's a bit better if you have a number of validation attributes.

提交回复
热议问题