Los resultados de la reflexión getProperty en "Coincidencia ambigua encontrada" en una propiedad nueva


¿Cómo puedo obtener mi propiedad? Actualmente se está produciendo un error de Ambiguous match found, consulte la línea de comentarios en el código.

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
}
Author: svick, 2012-07-12

6 answers

Tipo.getProperty

Situaciones en las que se produce AmbiguousMatchException ...

...derived type declara una propiedad que oculta una propiedad heredada con el mismo nombre, utilizando el nuevo modificador

Si ejecuta lo siguiente

var properties = myDE.GetType().GetProperties().Where(p => p.Name == "MyEntity");

Verá que se devuelven dos objetos PropertyInfo. Uno para MyBaseEntity y otro para MyDerivedEntity. Es por eso que está recibiendo el error Ambiguous match found.

Puede obtener el PropertyInfo para MyDerivedEntity así:

PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p => 
    p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));
 27
Author: Kevin Aenmey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 20:22:06

Para la propiedad:

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

Para el método:

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

BindingFlags .DeclaredOnly-Especifica que solo se deben considerar los miembros declarados al nivel de la jerarquía del tipo suministrado. Los miembros heredados no se consideran.

 18
Author: AlphaOmega,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-26 19:30:10

La ambigüedad se produce debido a la declaración new en MyDerivedEntity. Para superar esto puedes usar LINQ:

var type = myObject.GetType();
var colName = "MyEntity";
var all = type.GetProperties().Where(x => x.Name == colName);
var info = all.FirstOrDefault(x => x.DeclaringType == type) ?? all.First();

Esto tomará la propiedad del tipo derivado si existe, de lo contrario la base. Esto se puede voltear fácilmente si es necesario.

 11
Author: Chad Kuehn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-02 16:11:49

Kevin ya señaló el problema, pero no necesita declaraciones complejas, o LINQ para eso:

PropertyInfo propInfoSrcObj = myDE.GetType().
    GetProperty("MyEntity", typeof(MyDerivedEntity));
 6
Author: Lorenz Lo Sauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 20:48:55

Tengo este error en la consola del navegador Lo busco y encontré esta excepción es para c# y la respuesta es también para c# luego trato de mirar mi código y encontré el lugar donde se produce el problema:

Tengo un método post ajax y cuando posteo datos obtuve este error por lo que los datos que he pasado serán recopilados por el método web c#, por lo que cuando veo ese modelo tengo 2 propiedades con el mismo nombre, así que elimino una y el problema y la excepción se resolvieron.

 1
Author: Saurabh Solanki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 10:45:13

Estaba teniendo este problema con la serialización de MsgPack de mi objeto LocationKey. Terminaron siendo los operadores que había definido en mi clase LocationKey. Tener ambos operadores definidos causó que DefaultContext.GetSerializer(obj.GetType()); arrojara Coincidencias Ambiguas Encontradas al intentar serializar. La eliminación de un conjunto de operadores hizo que el problema desapareciera.

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;
}
 0
Author: odyth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-03 20:18:48