反射的getProperty结果"不明确的找到匹配"新特性 [英] GetProperty reflection results in "Ambiguous match found" on new property

查看:437
本文介绍了反射的getProperty结果"不明确的找到匹配"新特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能让我的财产?目前,一个错误是发生暧昧的比赛中发现,见代码注释行。

 公共类MyBaseEntity 
{
公共MyBaseEntity myEntity所获得{;组; }
}

公共类MyDerivedEntity:MyBaseEntity
{
公开新MyDerivedEntity myEntity所获得{;组; }
}

私有静态无效的主要(字串[] args)
{
MyDerivedEntity myDE =新MyDerivedEntity();

的PropertyInfo propInfoSrcObj = myDE.GetType()的getProperty(myEntity所);
// - 错误:不明确的匹配找到
}


解决方案

Type.GetProperty



在AmbiguousMatchException时...




情况

...派生类型声明隐藏继承属性与属性相同的名称,使用新修改




如果您运行以下

  VAR性能= myDE.GetType()的GetProperties()式。(p => p.Name ==myEntity所); 

您将看到两个的PropertyInfo 对象回。一个用于 MyBaseEntity ,一个用于 MyDerivedEntity 。这就是为什么您收到的暧昧找到匹配的错误。



您可以得到的PropertyInfo MyDerivedEntity 是这样的:

 的PropertyInfo propInfoSrcObj = myDE.GetType ().GetProperties()单。(p => 
p.Name ==myEntity所&放大器;&安培; p.PropertyType == typeof运算(MyDerivedEntity));


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
}

解决方案

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

If you run the following

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

you will see that two PropertyInfo objects are returned. One for MyBaseEntity and one for MyDerivedEntity. That is why you are receiving the Ambiguous match found error.

You can get the PropertyInfo for MyDerivedEntity like this:

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

这篇关于反射的getProperty结果"不明确的找到匹配"新特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆