[c#] GetProperty reflection results in “Ambiguous match found” on new property



2 Answers

For property:

MemberInfo property = myDE.GetProperty(
    "MyEntity",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

For method:

MemberInfo method = typeof(String).GetMethod(
    "ToString",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly,
    null,
    new Type[] { },// Method ToString() without parameters
    null);

BindingFlags.DeclaredOnly - Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.

Question

How can I get my property? Currently an error is occuring of Ambiguous match found, see the comment line in code.

public class MyBaseEntity
{
    public MyBaseEntity MyEntity { get; set; }
}

public class MyDerivedEntity : MyBaseEntity
{
    public new MyDerivedEntity MyEntity { get; set; }
}

private static void Main(string[] args)
{
    MyDerivedEntity myDE = new MyDerivedEntity();

    PropertyInfo propInfoSrcObj = myDE.GetType().GetProperty("MyEntity");
    //-- ERROR: Ambiguous match found
}



I was having this issue with MsgPack serialization of my LocationKey object. Ended up being the operators I had defined in my LocationKey class. Having both of these operators defined caused DefaultContext.GetSerializer(obj.GetType()); to throw Ambiguous Match Found when trying to serialize. Removing one set of operators made the issue go away.

public static bool operator ==(int key1, LocationKey key2)
{
    return key1 == key2.Value;
}

public static bool operator !=(int key1, LocationKey key2)
{
    return key1 != key2.Value;
}

public static bool operator ==(LocationKey key1, int key2)
{
    return key1.Value == key2;
}

public static bool operator !=(LocationKey key1, int key2)
{
    return key1.Value != key2;
}



Kevin already pointed out the issue, but you don't need complex statements, or LINQ for that:

PropertyInfo propInfoSrcObj = myDE.GetType().
    GetProperty("MyEntity", typeof(MyDerivedEntity));



Related