BindingFlags.DeclaredOnly alternative to avoid ambiguous properties of derived classes

Posted by JoeBilly on Stack Overflow See other posts from Stack Overflow or by JoeBilly
Published on 2010-04-27T10:59:51Z Indexed on 2010/04/27 11:03 UTC
Read the original article Hit count: 362

Filed under:
|
|

I'am looking for a solution to access 'flatten' (lowest) properties values of a class and its derived via reflection by property names.

ie access either Property1 or Property2 from the ClassB or ClassC type :

   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 virtual properties that are overrired (ie Property1 from ClassB). Then you get a AmbiguousMatchException because the searcher don't know if you want the property of the main class or the derived.

Using BindingFlags.DeclaredOnly avoid the AmbiguousMatchException but unoverrided virtual properties or derived classes properties are ommited (ie Property2 from ClassB).

Is there an alternative to this poor workaround :

// 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);

Furthermore, this workaround not resolve the reflection of 2nd level properties : getting Property1 from ClassC and AmbiguousMatchException is back.

My thoughts : I have no choice except loop... Erk... ??

I'am open to Emit, Lambda (is the Expression.Call can handle this?) even DLR solution.

Thanks !

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection