2010-03-03 5 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 

내 문제는 내가 주요 개체의 또 다른 특성 내부 때에 프로퍼티를 얻고 싶은 것입니다. 이 목표에 대한 간단한 방법이 있습니까?

미리 감사드립니다.

+2

typeof (CustomService) 대신 Type.GetType (typeof (CustomService) .ToString()) 이유는 무엇입니까? –

답변

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

먼저 다음 ID 상기 srv 특성을 참조하고를 취득해야합니다은 :

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