GetRuntimeProperties instead of GetProperty

I need to find a property inside a generic type. This is the old way (and since my code is for WinRT, I think I need a different approach):

PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetProperty(idField, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); 

I need to achieve the same result using GetRuntimeProperties . This is my approach:

 PropertyInfo pi = typeof(TRp).GenericTypeArguments[0].GetRuntimeProperties().Single(p => p.Name.ToUpper() == idField.ToUpper()... 

as you can see, I implemented IgnoreCase in my own way, maybe this can be done better?
How to implement the remaining BindingFlags ?

Thanks!

+5
source share
1 answer

You really don't need to. Here's how Type.GetRuntimeProperties implemented:

 public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) { CheckAndThrow(type); IEnumerable<PropertyInfo> properties = type.GetProperties(everything); return properties; } 

Where everything is defined as follows:

 private const BindingFlags everything = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; 

This means that he will already search for the flags you need.

Edit:

If you want to specify BindingFlags yourself, you can write your own extension method:

 public static class TypeExtensions { public static IEnumerable<PropertyInfo> GetAllProperties(this TypeInfo type, BindingFlags bindingFlags) { var propertyInfos = type.GetProperties(bindingFlags); var subtype = type.BaseType; if (subtype != null) list.AddRange(subtype.GetTypeInfo().GetAllProperties(bindingFlags)); return propertyInfos.ToArray(); } } 

Please note this has not been verified . It is just an attempt to show you that you can do it yourself.

+6
source

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


All Articles