2011-06-20 44 views
0

如何查找屬性的值?我需要檢查該值並將文本框maxlength設置爲該值。以下是我希望檢索的值的示例。如何查找屬性的值

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

你的意思是像return _LegalName? –

+0

我需要返回5一些如何。所以我可以設置文本框的最大長度爲5 – user698625

回答

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; 
      } 
    } 
} 
+0

完全想要我想要的感謝。 – user698625