C# 创建一个方法来遍历对象属性

C# 创建一个方法来遍历对象属性,c#,wcf,C#,Wcf,有没有办法编写代码来执行此操作: MyObject中的Foreach属性; 检查属性是否在IsRequired=true的is上有DataMember验证程序 [DataMember(Order = 2, IsRequired=true)] public string AddressLine1 { get; set; } [DataMember(Order = 3)] public string AddressLine2 { get; set; } 如果是,检查对象中是否有notNull或空

有没有办法编写代码来执行此操作:

MyObject中的Foreach属性; 检查属性是否在IsRequired=true的is上有DataMember验证程序

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

[DataMember(Order = 3)]
public string AddressLine2 { get; set; }
如果是,检查对象中是否有notNull或空值

总之,我创建了一个名为CheckForRequiredFields(对象o)的方法


在这种情况下,使用上面列出的属性向其传递一个“Address”对象。代码看到第一个属性has RequiredField=true,因此它检查传递给它的Address对象是否有AddressLine1的值是的,有。看一看。您可以获取您的类型,对其调用
type.GetProperties()
,并为每个属性检索
PropertyInfo

PropertyInfo
可以获取其属性(使用
GetCustomAttributes
方法),并查找
DataMember
属性。如果您找到了一个,请检查它的
IsRequired

类似内容(从内存中,因此不保证正确性):


您是否知道.NET已经有一组类在DataAnnotations命名空间中提供此功能?
Attributes
属性不会告诉他们该属性是否用自定义属性修饰(这就是
GetCustomAttributes
的作用)。
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
}