【问题标题】:Get the type of an Object which is a property of another object获取作为另一个对象属性的对象的类型
【发布时间】:2010-10-14 09:42:04
【问题描述】:

为了解释,假设我有一个 Company 对象,它具有 Address 类型的 Address 属性。所以它会是这样的:

公共类公司 { 地址公司地址; } 公开课地址 { 整数; 字符串街道名称; }

现在我有一个适用于任何类型对象类型的方法,我想从接收到的对象中获取特定属性,所以我正在尝试以下方法:

公共字符串我的方法(对象我的对象,字符串属性名称) { 类型 objectType = myObject.GetType(); object internalObject = objectType.GetProperty("地址"); 类型 internalType = internalObject.GetType(); PropertyInfo singleProperty = internalType.GetProperty("StreetName"); 返回 singleProperty.GetValue(internalObject, null).ToString(); }

问题是 internalType 从来不是 Address 而是 "System.Reflection.RuntimePropertyInfo" 所以 singleProperty 总是为空;

我怎样才能做到这一点?

谢谢。

【问题讨论】:

    标签: .net reflection


    【解决方案1】:

    您的代码的问题是internalObject 将是GetProperty 方法返回的PropertyInfo 对象。您需要获取该属性的实际值,因此需要调用 GetValue 方法。

    public string MyMethod(object myObject, string propertyName) {
        Type objectType = myObject.GetType();
        object internalObject = objectType.GetProperty("Address").GetValue(myObject, null);
    
        Type internalType = internalObject.GetType();
        PropertyInfo singleProperty = internalType.GetProperty("StreetName");
    
        return singleProperty.GetValue(internalObject, null).ToString(); 
    }
    

    【讨论】:

      【解决方案2】:

      internalObject 只是一个 PropertyInfo 对象,就像 singleProperty 一样。

      您应该使用相同的技术来提取实际对象:

          PropertyInfo addressProperty = objectType.GetProperty("Address");
      
          object interalObject = addressProperty.GetValue(myObject);
      

      其余的都是正确的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-03
        • 2022-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        • 1970-01-01
        相关资源
        最近更新 更多