使用反射的模糊异常

时间:2010-11-11 06:07:31

标签: c# .net reflection

有没有解决这个问题的方法?

采取以下代码......

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

第'line.GetType()。getProperty(“Name”)'throws b / c Parent和Child之间的名称不明确。我想要来自Child的“姓名”。有没有办法做到这一点?

我尝试了各种绑定标志而没有运气。

1 个答案:

答案 0 :(得分:5)

添加一些BindingFlags

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

DeclaredOnly表示:

  

指定只应考虑在提供的类型层次结构级别声明的成员。不考虑继承的成员。

或使用LINQ的替代方法(可以轻松添加任何异常检查,例如检查Attribute.IsDefined):

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