GetPropertyreflection导致新属性中出现“模糊匹配”
我如何获得我的财产? 目前Ambiguous match found
的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 }
Type.GetProperty
出现AmbiguousMatchException的情况……
…派生类型声明了一个属性,该属性使用new修饰符隐藏具有相同名称的inheritance属性
如果您运行以下
var properties = myDE.GetType().GetProperties().Where(p => p.Name == "MyEntity");
您将看到返回两个PropertyInfo
对象。 一个用于MyBaseEntity
,另一个用于MyDerivedEntity
。 这就是您收到Ambiguous match found错误的原因。
您可以像这样获取MyDerivedEntity
的PropertyInfo
:
PropertyInfo propInfoSrcObj = myDE.GetType().GetProperties().Single(p => p.Name == "MyEntity" && p.PropertyType == typeof(MyDerivedEntity));
对于财产:
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 – 指定只应考虑在提供的类型的层次结构级别声明的成员。 不考虑inheritance的成员。
由于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();
这将从派生类型中获取属性(如果存在),否则为基础。 如果需要,这可以很容易地翻转。
Kevin已经指出了这个问题,但你不需要复杂的语句或LINQ:
PropertyInfo propInfoSrcObj = myDE.GetType(). GetProperty("MyEntity", typeof(MyDerivedEntity));
我在浏览器控制台中遇到此错误我搜索它并且我发现此exception是针对c#而且答案也是针对c#然后我尝试查看我的代码并找到问题发生的位置:
我有一个ajax post方法,当我发布数据时出现此错误,因此我传递的数据将通过c#web方法收集,所以当我看到该模型时,我有2个具有相同名称的属性,所以我删除了一个问题和exception解决了
我在使用LocationKey对象的MsgPack序列化时遇到了这个问题。 结束了我在LocationKey类中定义的运算符。 定义了这两个运算符导致DefaultContext.GetSerializer(obj.GetType());
尝试序列化时发现Ambiguous Match Found。 删除一组操作员使问题消失。
public static bool operator ==(int key1, LocationKey key2) { return key1 == key2.Value; } public static bool operator !=(int key1, LocationKey key2) { return key1 != key2.Value; } public static bool operator ==(LocationKey key1, int key2) { return key1.Value == key2; } public static bool operator !=(LocationKey key1, int key2) { return key1.Value != key2; }