我怎样才能得到我的属性(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
}
最佳答案
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
。这就是您收到找到模糊匹配错误的原因。
您可以像这样获取 MyDerivedEntity
的 PropertyInfo
:
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/