Reputation: 3491
I have a class by 3 property.
class Issuance
{
[MyAttr]
virtual public long Code1 { get; set; }
[MyAttr]
virtual public long Code2 { get; set; }
virtual public long Code3 { get; set; }
}
I need to select some of properties in this class by my custom attribute([MyAttr]
).
I use of GetProperties()
But this return all properties.
var myList = new Issuance().GetType().GetProperties();
//Count of result is 3 (Code1,Code2,Code3) But count of expected is 2(Code1,Code2)
How can I do it?
Upvotes: 1
Views: 1747
Reputation: 14012
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getcustomattributes.aspx
Try this - basically do a foreach on the properties and see if you get back your attribute type for each property. If you do, that property has the attribute:
e.g.
foreach(var propInfo in new Issuance().GetType().GetProperties())
{
var attrs = propInfo.GetCustomAttributes(typeof(MyAttr), true/false); // Check docs for last param
if(attrs.Count > 0)
// this is one, do something
}
Upvotes: 0
Reputation: 1499760
Just use LINQ and a Where
clause using MemberInfo.IsDefined
:
var myList = typeof(Issuance).GetProperties()
.Where(p => p.IsDefined(typeof(MyAttr), false);
Upvotes: 8