2010-03-03 4 views
0

J'essaie d'utiliser la réflexion pour une raison quelconque et j'ai eu ce problème.C# Réflexion Problème

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 

Mon problème est que je veux obtenir une propriété dans une autre propriété de l'objet principal. Existe-t-il un moyen simple d'atteindre cet objectif?

Merci à l'avance.

+2

Pourquoi Type.GetType (typeof (CustomService) .ToString()) au lieu de typeof (CustomService)? –

Répondre

1

Vous avez à réfléchir sur le service personnalisé et trouver la valeur de la propriété. Après cela, vous devez réfléchir sur cette propriété et trouver sa valeur. Comme si:

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

Vous devez d'abord obtenir une référence à la propriété srv puis le 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); 
    } 
}