2012-03-05 133 views
1

是否有任何方法來使用代碼來執行此操作:創建一種方法來迭代通過對象屬性

Foreach property in MyObject; 檢查屬性是否有一個DataMember驗證器是IsRequired = true;

[DataMember(Order = 2, IsRequired=true)] 
public string AddressLine1 { get; set; } 

[DataMember(Order = 3)] 
public string AddressLine2 { get; set; } 

如果是這樣,檢查對象是否有一個notNull或空值;

因此,在總結我創建一個名爲CheckForRequiredFields(對象o)

傳一個「地址」對象在這種情況下與上述列出的屬性的方法。代碼看到第一個屬性爲RequiredField = true,因此它檢查傳遞給它的Address對象具有AddressLine1的值。

+1

你知道.NET已經擁有了一套能夠提供在DataAnnotations命名空間中此功能的類? http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx – 2012-03-05 19:23:35

回答

1

喜歡的東西(從內存中,因此不正確的擔保):

foreach(var propInfo in o.GetType().GetProperties()) 
{ 
    var dmAttr = propInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute; 
    if (dmAttr == null) 
     continue; 

    object propValue = propInfo.GetValue(o, null); 
    if (dmAttr.IsRequired && propValue == null) 
     // It is required but does not have a value... do something about it here 
} 
+0

非常感謝,有一點調整 – 2012-03-05 20:39:01

1

是的,有。看看Reflection。您可以輸入您的類型,然後撥打Type.GetProperties()併爲每個屬性檢索PropertyInfo

PropertyInfo您可以獲得其屬性(使用GetCustomAttributes方法),並查找DataMember屬性。如果找到,請檢查它的IsRequired

+0

'Attributes'屬性不會告訴他們屬性是否使用自定義屬性進行修飾(這就是'GetCustomAttributes'的用途)。 – 2012-03-05 19:38:26

+0

更正。謝謝。 – zmbq 2012-03-05 19:41:20