0

如何找到属性的值?我需要检查该值并将文本框 maxlength 设置为该值。这是我要检索的值的示例。

public class DogClass
    {
        [StringLength(5)]
        public string LegalName
        {
        }
4

1 回答 1

0

您可以使用反射来获取此信息。下面是一个可以帮助您入门的片段。

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;
           }
    }
}
于 2011-06-21T12:20:36.133 回答