如何查找属性的值

时间:2011-06-20 19:01:21

标签: sql winforms entity-framework-mapping

如何找到属性的值?我需要检查值并将textbox maxlength设置为该值。这是我想要检索的值的一个例子。

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

1 个答案:

答案 0 :(得分: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;
           }
    }
}