开发者

How to find the value of an attribute

开发者 https://www.devze.com 2023-03-14 01:03 出处:网络
How can I find the value of an attribute? I need to check the value and set the textbox maxlength to that value. Here is an example of the value I\'m looking to retrieve.

How can I find the value of an attribute? I need to check the value and set the textbox maxlength to that value. Here is an example of the value I'm looking to retrieve.

public class DogClass
    {
        [StringLength(5)]
        public string LegalNam开发者_StackOverflowe
        {
        }


You can use reflection to get this info. Below is a snippet that should get you started.

protected void GetStringLength(object objDog) {
    // loop through each property in object
    foreach (PropertyInfo pi in objDog.GetType().GetProperties())
    {
        // for each object property, get the SringLength tag (if there is one)
        foreach (Attribute attribute in Attribute.GetCustomAttributes(pi, typeof(StringLengthAttribute), true))
           {
                // we'll assume there is only one 
                var stringLenVal = (attribute as StringLengthAttribute).MaximumLength;
                break;
           }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消