Ambiguous exception using reflection

Is there any way to solve this problem?

Take the following code ...

namespace ReflectionResearch
{
 class Program
 {
  static void Main(string[] args)
  {
   Child child = new Child();

   child.GetType().GetProperty("Name");
  }
 }

 public class Parent
 {
  public string Name
  {
   get;
   set;
  }
 }

 public class Child : Parent
 {
  public new int Name
  {
   get;
   set;
  }
 }
}

String 'child.GetType (). GetProperty ("Name") 'throws b / c Name is ambiguous between parent and child. I want a "Name" from a child. Is there any way to do this?

I have tried various anchor flags with no luck.

+3
source share
1 answer

Add a few BindingFlags:

child.GetType().GetProperty("Name",
     BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);

DeclaredOnly means:

Indicates that only members declared at the hierarchy level of the supplied type should be considered. Inherited members are not counted.

, LINQ ( , , Attribute.IsDefined):

child.GetType().GetProperties().Single(
    prop => prop.Name == "Name" && prop.DeclaringType == typeof(Child));
+5

Source: https://habr.com/ru/post/1774229/


All Articles