BindingFlags.Declared A nightly alternative to avoid the ambiguous properties of derived classes (AmbiguousMatchException)

I am looking for a solution for accessing the flatten (lowest) values ​​of a class property and its derivative by reflection with property names.

those. access Property1 or Property2 from class ClassB or ClassC:

   public class ClassA
    {
        public virtual object Property1 { get; set; }

        public object Property2 { get; set; }
    }
    public class ClassB : ClassA
    {
        public override object Property1 { get; set; }
    }
    public class ClassC : ClassB
    {
    }

Using simple reflection works until you have restored virtual properties (i.e. Property1 from ClassB). Then you get an AmbiguousMatchException because the crawler does not know if you want a property of the main class or derivative.

Using BindingFlags.Declared; Avoid AmbiguousMatchException exceptionally, but the properties of unoverrided virtual properties or derived classes are omitted (i.e. Property2 from ClassB).

:

// Get the main class property with the specified propertyName
PropertyInfo propertyInfo = _type.GetProperty(propertyName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

    // If not found, get the property wherever it is
    if (propertyInfo == null)
            propertyInfo = _type.GetProperty(propertyName);

, 2- : Property1 ClassC AmbiguousMatchException.

: , ... Erk...??

Emit, Lambda ( Expression.Call ?) DLR-.

!

+3
2

- .

​​, Fasterflect. , .

// find properties and remove duplicates higher up the hierarchy
var properties = type.Properties( Flags.ExcludeBackingMembers );
+4

Fasterflect:

foreach (PropertyInfo propertyInfo in objType.Properties(Flags.ExcludeBackingMembers | Flags.Public | Flags.Static | Flags.Instance))
{
    FasterflectPropertyValue(propertyInfo.Name, obj);
}

private static object FasterflectPropertyValue(string propertyName, object obj)
{
    return obj.GetPropertyValue(propertyName);
}

Reflection from Class1 - 1 loops :3602674ticks
Reflection from Class2 - 1 loops :2940541ticks
Reflection from Class3 - 1 loops :1035300ticks
Reflection from Class1 - 100 loops :2ms
Reflection from Class2 - 100 loops :2ms
Reflection from Class3 - 100 loops :3ms
Reflection from Class1 - 10000 loops :274ms
Reflection from Class2 - 10000 loops :284ms
Reflection from Class3 - 10000 loops :295ms
Fasterflect from Class1 - 1 loops :44ms
Fasterflect from Class2 - 1 loops :2508656ticks
Fasterflect from Class3 - 1 loops :2314142ticks
Fasterflect from Class1 - 100 loops :3223064ticks
Fasterflect from Class2 - 100 loops :5056514ticks
Fasterflect from Class3 - 100 loops :5166725ticks
Fasterflect from Class1 - 10000 loops :96ms
Fasterflect from Class2 - 10000 loops :138ms
Fasterflect from Class3 - 10000 loops :162ms

0

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


All Articles