GetProperty reflection results in “Ambiguous match found” on new property

前端 未结 7 1160
离开以前
离开以前 2020-12-30 19:25

How can I get my property? Currently an error is occuring of Ambiguous match found, see the comment line in code.

public class MyBaseEntity
{
           


        
7条回答
  •  鱼传尺愫
    2020-12-30 20:19

    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));
    

提交回复
热议问题