2009-03-19 14 views
1

説明のために、アドレス型のAddressプロパティを持つCompanyオブジェクトがあるとしましょう。今私は、オブジェクト型のいずれかの種類で動作する方法を持っていると私は受け取ったオブジェクトから特定のプロパティを取得したいので、私は次のことをしようとしている別のオブジェクトのプロパティであるオブジェクトの型を取得する

 
public class Company 
{ 
    Address CompanyAddress; 
} 

public class Address 
{ 
    int Number; 
    string StreetName; 
} 

ので、それはようなものになるだろう
 
public string MyMethod(object myObject, string propertyName) 
{ 
    Type objectType = myObject.GetType(); 
    object internalObject = objectType.GetProperty("Address"); 

    Type internalType = internalObject.GetType(); 
    PropertyInfo singleProperty = internalType.GetProperty("StreetName"); 

    return singleProperty.GetValue(internalObject, null).ToString(); 
} 

問題は、internalTypeはAddressではなく "System.Reflection.RuntimePropertyInfo"なので、singlePropertyは常にnullです。

どうすればこの問題を解決できますか?

ありがとうございます。

答えて

2

コードに問題があると、internalObjectGetPropertyメソッドによって返された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(); 
} 
+0

これは完璧です。どうもありがとうございます !!!! –

0

internalObjectは、singlePropertyのように単なるPropertyInfoオブジェクトです。

あなたは、実際のオブジェクトを抽出するために、同じ技術を使用する必要があります。

PropertyInfo addressProperty = objectType.GetProperty("Address"); 

    object interalObject = addressProperty.GetValue(myObject); 

残りは正しいです。

関連する問題