c# - Get all properties marked with [JsonIgnore] attribute -


i have class myclass list of properties.

public class myclass {     [attribute1]     [attribute2]     [jsonignore]     public int? prop1 { get; set; }      [attribute1]     [attribute8]     public int? prop2 { get; set; }      [jsonignore]     [attribute2]     public int prop3 { get; set; } } 

i retrieve properties no marked [jsonignore] attribute.

jsonignore attribute http://www.newtonsoft.com/json

so, in example, have property "prop2".

i tried

var props = t.getproperties().where(                 prop => attribute.isdefined(prop, typeof(jsonignore))); 

or

var props = t.getproperties().where(                     prop => attribute.isdefined(prop, typeof(newtonsoft.json.jsonignoreattribute))); 

where t type of myclass method return 0 elements.

can me, please? thanks

typeof(myclass).getproperties()                .where(property =>                        property.getcustomattributes(false)                               .oftype<jsonignoreattribute>()                               .any()                      ); 

specifying type in getcustomattibutes call can more performant, in addition, might want logic reusable use helper method:

static ienumerable<propertyinfo> getpropertieswithattribute<ttype, tattribute>() {     func<propertyinfo, bool> matching =              property => property.getcustomattributes(typeof(tattribute), false)                                 .any();      return typeof(ttype).getproperties().where(matching); } 

usage:

var properties = getpropertywithattribute<myclass, jsonignoreattribute>(); 

edit: i'm not sure, might after properties without attribute, negate find predicate:

static ienumerable<propertyinfo> getpropertieswithoutattribute<ttype, tattribute>() {     func<propertyinfo, bool> matching =             property => !property.getcustomattributes(typeof(tattribute), false)                                 .any();      return typeof(ttype).getproperties().where(matching); } 

or use simple libraries such fasterflect:

typeof(myclass).propertieswith<jsonignoreattribute>(); 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -