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

前端 未结 7 1170
离开以前
离开以前 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:30

    The ambiguity occurs because of the new declaration in MyDerivedEntity. To overcome this you can use 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();
    

    This will grab the property out of the derived type if it exists, otherwise the base. This can easily be flip-flopped if needed.

提交回复
热议问题