我怎样才能得到我的财产?当前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
}发布于 2012-07-12 09:08:42
Type.GetProperty
发生AmbiguousMatchException的
情况...
...derived类型声明一个属性,该属性通过使用new修饰符隐藏具有相同名称的继承属性
如果您运行以下命令
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));发布于 2014-02-27 03:30:11
对于属性:
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 -指定只应考虑在所提供类型的层次结构级别上声明的成员。继承的成员不被考虑。
发布于 2015-11-03 00:11:49
这种歧义是由于MyDerivedEntity中的new声明造成的。要克服这一点,您可以使用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();这将从派生类型中获取属性(如果存在),否则将从基类中获取属性。如果需要,这可以很容易地进行翻转。
https://stackoverflow.com/questions/11443707
复制相似问题