2012-03-05 13 views
1

これを行うコードを書く方法はありますか。オブジェクトを反復処理するメソッドを作成する

ForeachプロパティはMyObject、 プロパティにDataMemberバリデータがあるかどうかを確認するにはIsRequired = true;

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

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

オブジェクトにnotNullまたは空の値があるかどうかを確認します。

だから要約でIはCheckForRequiredFields呼ばれる方法(オブジェクトo)

パスを上記の特性を有する、この場合の「アドレス」オブジェクトを作成します。コード最初のプロパティにRequiredField = trueが渡されたため、渡されたAddressオブジェクトにAddressLine1の値があることが確認されます

+1

をご存知でしたか? http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx –

答えて

1

ような何か(正しさのメモリからありませんので保証):あなたは.NETがすでにDataAnnotations名前空間にこの機能を提供するクラスのセットを持ってい

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

ちょっと微調整してくれてありがとう –

1

はい、あります。 Reflectionをご覧ください。あなたはあなたのタイプを取ることができます。Type.GetProperties()を呼び出し、それぞれのプロパティに対してPropertyInfoを取得します。

PropertyInfoからは、GetCustomAttributesメソッドを使用してその属性を取得し、DataMember属性を探します。見つかった場合は、IsRequiredを確認してください。

+0

'Attributes'プロパティは、プロパティがカスタム属性で修飾されているかどうかを知らせません(' GetCustomAttributes'が)。 –

+0

修正済み。ありがとう。 – zmbq

関連する問題