2010-03-03 76 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); 
    } 
}