8

Web フォーム プロジェクトのカスタム属性検証を作成しようとしています。

私はすでに自分のクラスからすべてのプロパティを取得できますが、それらをフィルタリングして属性を持つプロパティを取得する方法がわかりません。

例えば:

PropertyInfo[] fields = myClass.GetType().GetProperties();

これにより、すべてのプロパティが返されます。しかし、たとえば「testAttribute」のような属性を使用してプロパティを返すにはどうすればよいですか?

私はすでにこれについて検索しましたが、これを解決しようとしてしばらくした後、ここで質問することにしました。

4

4 に答える 4

24

使用Attribute.IsDefined:

PropertyInfo[] fields = myClass.GetType().GetProperties()
    .Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false))
    .ToArray();
于 2011-05-09T23:16:07.513 に答える
10
fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0)

のドキュメントをGetCustomAttributes()参照してください。

于 2011-05-09T23:09:22.760 に答える
3

使用できます

    .Any()

表現を簡素化する

    fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())
于 2013-07-31T09:48:16.127 に答える
1

おそらく、MemberInfo のGetCustomAttributesメソッドが必要です。特にTestAttributeなどを探している場合は、次を使用できます。

foreach (var propInfo in fields) {
    if (propInfo.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0) {
        // Do some stuff...
    }      
}

または、それらすべてを取得する必要がある場合:

var testAttributes = fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0);
于 2011-05-09T23:09:56.760 に答える