c# - GetProperty 反射在新属性上产生 "Ambiguous match found"

标签 c# reflection system.reflection

我怎样才能得到我的属性(property)?当前发生错误 找到不明确的匹配项,请参阅代码中的注释行。

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
}

最佳答案

Type.GetProperty

Situations in which AmbiguousMatchException occurs ...

...derived type declares a property that hides an inherited property with the same name, by using the new modifier

如果你运行以下命令

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

您会看到返回了两个 PropertyInfo 对象。一个用于 MyBaseEntity,一个用于 MyDerivedEntity。这就是您收到找到模糊匹配错误的原因。

您可以像这样获取 MyDerivedEntityPropertyInfo:

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

关于c# - GetProperty 反射在新属性上产生 "Ambiguous match found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443707/

相关文章:

java - 使用反射根据泛型类的getClass创建实例

c# - EF Core 从元数据获取反向导航属性

reflection - 如何使用反射实现或模拟Go接口(interface)?

.net - 如何从.NET解决方案构建 'dependency tree diagram'

reflection - 通过反射获取 cmdlet 的动态参数

c# - 从 Attribute 走到 CustomAttributeData 或向后

c# - ASP.net 网络 API 2 错误 "The parameters dictionary contains a null entry for parameter"

c# - 达到上传文件的最大长度

c# - 请为我破译这个 C# 表达式

c# - 为什么 Task.FromResult 需要显式转换?