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

前端 未结 7 1162
离开以前
离开以前 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.

    0 讨论(0)
提交回复
热议问题