2010-03-03 124 views
0

我試圖使用反射出於某種原因,我陷入了這個問題。c#反射問題

class Service 
{ 
    public int ID {get; set;} 
    . 
    . 
    . 
} 

class CustomService 
{ 
    public Service srv {get; set;} 
    . 
    . 
    . 
} 

//main code 

Type type = Type.GetType(typeof(CustomService).ToString()); 
PropertyInfo pinf = type.GetProperty("Service.ID"); // returns null 

我的問題是,我想獲得一個propery裏面的主要對象的另一個屬性。 有沒有一個簡單的方法來實現這個目標?

在此先感謝。

+2

爲什麼Type.GetType(typeof(CustomService).ToString())而不是typeof(CustomService)? –

回答

1

你必須反思定製服務,並找到屬性值。之後,你必須反思該財產,並找到它的價值。像這樣:

var customService = new CustomService(); 
customService.srv = new Service() { ID = 409 }; 
var srvProperty = customService.GetType().GetProperty("srv"); 
var srvValue = srvProperty.GetValue(customService, null); 
var id = srvValue.GetType().GetProperty("ID").GetValue(srvValue, null); 
Console.WriteLine(id); 
5

您需要首先獲取對srv屬性的引用,然後ID

class Program 
{ 
    class Service 
    { 
     public int ID { get; set; } 
    } 

    class CustomService 
    { 
     public Service srv { get; set; } 
    } 

    static void Main(string[] args) 
    { 
     var serviceProp = typeof(CustomService).GetProperty("srv"); 
     var idProp = serviceProp.PropertyType.GetProperty("ID"); 

     var service = new CustomService 
     { 
      srv = new Service { ID = 5 } 
     }; 

     var srvValue = serviceProp.GetValue(service, null); 
     var idValue = (int)idProp.GetValue(srvValue, null); 
     Console.WriteLine(idValue); 
    } 
}