2012-03-05 82 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