Reflection of a property to get attributes. How to do it when they are defined elsewhere?

I have a Bar class as follows:

class Foo : IFoo { [Range(0,255)] public int? FooProp {get; set} } class Bar : IFoo { private Foo foo = new Foo(); public int? FooProp { get { return foo.FooProp; } set { foo.FooProp= value; } } } 

I need to find the [Range (0.255)] attribute reflecting ONLY on the Bar.FooProp property. I mean, prop is decorated with an instance of the class (.. new Foo ()) not in the class when I am currently parsing. Infact Bar.FooProp has no attributes

EDIT

I moved the attributes to the interface definition, so I need to parse the inherited interfaces to find them. I can do this because the Bar class must implement IFoo. In this particular case, I was lucky, but the problem remains when I do not have interfaces ... I will notice next time

 foreach(PropertyInfo property in properties) { IList<Type> interfaces = property.ReflectedType.GetInterfaces(); IList<CustomAttributeData> attrList; foreach(Type anInterface in interfaces) { IList<PropertyInfo> props = anInterface.GetProperties(); foreach(PropertyInfo prop in props) { if(prop.Name.Equals(property.Name)) { attrList = CustomAttributeData.GetCustomAttributes(prop); attributes = new StringBuilder(); foreach(CustomAttributeData attrData in attrList) { attributes.AppendFormat(ATTR_FORMAT, GetCustomAttributeFromType(prop)); } } } } 
+4
source share
2 answers

I had a similar situation some time ago, when I had an attribute declared in a method in an interface, and I wanted to get an attribute from a method for a type that implements the interface. For instance:

 interface I { [MyAttribute] void Method( ); } class C : I { void Method( ) { } } 

The code below is used to check the entire interface implemented by this type, see which interface elements this method provides (using GetInterfaceMap ) and returns any attributes of these members. Right before that, I also check to see if an attribute is present in the method itself.

 IEnumerable<MyAttribute> interfaceAttributes = from i in method.DeclaringType.GetInterfaces( ) let map = method.DeclaringType.GetInterfaceMap( i ) let index = GetMethodIndex( map.TargetMethods, method ) where index >= 0 let interfaceMethod = map.InterfaceMethods[index] from attribute in interfaceMethod.GetCustomAttributes<MyAttribute>( true ) select attribute; ... static int GetMethodIndex( MethodInfo[] targetMethods, MethodInfo method ) { return targetMethods.IndexOf( target => target.Name == method.Name && target.DeclaringType == method.DeclaringType && target.ReturnType == method.ReturnType && target.GetParameters( ).SequenceEqual( method.GetParameters( ), PIC ) ); } 
+2
source

When looking at FooProp there is nothing to identify the existence of a Foo (at any point). Perhaps you could add an attribute to define the Foo field and think about it (via FieldInfo.FieldType )?

+1
source

Source: https://habr.com/ru/post/1286511/


All Articles