GetProperty反射导致新属性上出现“模糊匹配”

问题描述 投票:28回答:7

我如何获得我的财产?目前Ambiguous match found发生错误,请参阅代码中的注释行。

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
}
c# reflection system.reflection
7个回答
33
投票

Type.GetProperty

出现AmbiguousMatchException的情况......

...派生类型声明一个属性,该属性使用new修饰符隐藏具有相同名称的继承属性

如果您运行以下

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

你会看到返回两个PropertyInfo对象。一个用于MyBaseEntity,一个用于MyDerivedEntity。这就是您收到Ambiguous match found错误的原因。

你可以像这样获得PropertyInfoMyDerivedEntity

PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p => 
    p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));

24
投票

对于财产:

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

方法:

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

BindingFlags.DeclaredOnly - 指定只应考虑在提供的类型层次结构级别声明的成员。不考虑继承的成员。


12
投票

由于new中的MyDerivedEntity声明,出现歧义。为了克服这个问题,您可以使用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();

这将从派生类型中获取属性(如果存在),否则为基础。如果需要,这可以很容易地翻转。


8
投票

Kevin已经指出了这个问题,但你不需要复杂的语句或LINQ:

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

1
投票

我在浏览器控制台中遇到此错误我搜索它并且我发现此异常是针对c#而且答案也是针对c#然后我尝试查看我的代码并找到问题发生的位置:

我有一个ajax post方法,当我发布数据时出现此错误,因此我传递的数据将通过c#web方法收集,所以当我看到该模型时,我有2个具有相同名称的属性,所以我删除了一个问题和异常得到了解决


0
投票

我在使用LocationKey对象的MsgPack序列化时遇到了这个问题。结束了我在LocationKey类中定义的运算符。定义了这两个运算符会导致DefaultContext.GetSerializer(obj.GetType());在尝试序列化时抛出Ambiguous Match Found。删除一组操作员使问题消失。

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
投票

对我来说,在VB.Net中,我在将JS对象传递给<WebMethod()>函数时遇到了这个超级描述性错误。

My Object由EF实体组成,其中包含对其他实体的引用。将这些引用属性设置为无解决此问题。不知道为什么在序列化发送给JS时没有引起循环引用,但确实如此。

© www.soinside.com 2019 - 2024. All rights reserved.