开发者

Ambiguous exception using reflection

Is there a way around this issue?

Take the following code...

namespac开发者_开发技巧e 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;
  }
 }
}

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

I tried various binding flags with no luck.


Add some BindingFlags:

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

DeclaredOnly means:

Specifies that only members declared at the level of the supplied type's hierarchy should be considered. Inherited members are not considered.

Or an alternative using LINQ (which makes it easy to add any unusual checks, for example checking Attribute.IsDefined):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜