反射的getProperty结果"不明确的找到匹配"新特性 [英] GetProperty reflection results in "Ambiguous match found" on new property
问题描述
我怎样才能让我的财产?目前,一个错误是发生暧昧的比赛中发现
,见代码注释行。
公共类MyBaseEntity
{
公共MyBaseEntity myEntity所获得{;组; }
}
公共类MyDerivedEntity:MyBaseEntity
{
公开新MyDerivedEntity myEntity所获得{;组; }
}
私有静态无效的主要(字串[] args)
{
MyDerivedEntity myDE =新MyDerivedEntity();
的PropertyInfo propInfoSrcObj = myDE.GetType()的getProperty(myEntity所);
// - 错误:不明确的匹配找到
}
在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 }
解决方案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 forMyBaseEntity
and one forMyDerivedEntity
. That is why you are receiving the Ambiguous match found error.You can get the
PropertyInfo
forMyDerivedEntity
like this:PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p => p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));
这篇关于反射的getProperty结果"不明确的找到匹配"新特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!