代码之家  ›  专栏  ›  技术社区  ›  John Livermore

使用反射的不明确异常

  •  3
  • John Livermore  · 技术社区  · 14 年前

    有办法解决这个问题吗?

    采用以下代码…

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

    “child.getType().getProperty(“name”)行引发的b/c名称在父级和子级之间不明确。我要孩子的名字。有办法吗?

    我试过各种各样的绑旗,但运气不好。

    1 回复  |  直到 14 年前
        1
  •  5
  •   Marc Gravell    14 年前

    添加一些 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));