2012-09-06 14 views
14

Estoy tratando de establecer un valor a una Propiedad de clase anidada dinámicamente mediante la reflexión. ¿Alguien podría ayudarme a hacer esto?Cómo establecer vaues a la propiedad anidada usando C# Reflection.?

Estoy teniendo una clase Region como a continuación.

public class Region 
{ 
    public int id; 
    public string name; 
    public Country CountryInfo; 
} 

public class Country 
{ 
    public int id; 
    public string name; 
} 

Tengo un lector de datos Oracle para proporcionar los valores del cursor Ref.

que me dará como

de identificación, nombre, country_id, COUNTRY_NAME

pude capaz de asignar los valores a la Region.Id, Region.Name por debajo.

FieldName="id" 
prop = objItem.GetType().GetProperty(FieldName, BindingFlags.Public | BindingFlags.Instance); 
prop.SetValue(objItem, Utility.ToLong(reader_new[ResultName]), null); 

Y para la propiedad Nested pude capaz de hacer los valores asignar a la que más adelante mediante la creación de una instancia leyendo el nombre del campo.

FieldName="CountryInfo.id" 

if (FieldName.Contains('.')) 
{ 
    Object NestedObject = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); 

    //getting the Type of NestedObject 
    Type NestedObjectType = NestedObject.GetType(); 

    //Creating Instance 
    Object Nested = Activator.CreateInstance(typeNew); 

    //Getting the nested Property 
    PropertyInfo nestedpropinfo = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); 

    PropertyInfo[] nestedpropertyInfoArray = nestedpropinfo.PropertyType.GetProperties(); 
    prop = nestedpropertyInfoArray.Where(p => p.Name == Utility.Trim(FieldName.Split('.')[1])).SingleOrDefault(); 

    prop.SetValue(Nested, Utility.ToLong(reader_new[ResultName]), null); 
    Nestedprop = objItem.GetType().GetProperty(Utility.Trim(FieldName.Split('.')[0]), BindingFlags.Public | BindingFlags.Instance); 

    Nestedprop.SetValue(objItem, Nested, null); 
} 

Los valores de asignación anteriores a Country.Id.

Pero como estoy creando una instancia todas y cada una de las veces no pude obtener el valor Country.Id anterior si selecciono el nombre siguiente del país.

Podría alguien decir podría asignar valores al objItem(that is Region).Country.Id y objItem.Country.Name. Lo que significa cómo asignar valores a las propiedades anidadas en lugar de crear una instancia y asignar cada vez.

Gracias de antemano.!

+1

duplicado Posible de http://stackoverflow.com/questions/1954746/using-reflection -in-c-sharp-to-get-properties-of-a-nested-object –

Respuesta

35

Debe estar llamando PropertyInfo.GetValue utilizando la propiedad Country para sacar al país, a continuación, utilizando la propiedad PropertyInfo.SetValueId a establecer la ID en el país.

Así que algo como esto:

public void SetProperty(string compoundProperty, object target, object value) 
{ 
    string[] bits = compoundProperty.Split('.'); 
    for (int i = 0; i < bits.Length - 1; i++) 
    { 
     PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]); 
     target = propertyToGet.GetValue(target, null); 
    } 
    PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last()); 
    propertyToSet.SetValue(target, value, null); 
} 
+0

Gracias Estimado ... Funcionó como un encanto ... :-) – Sravan

+0

¿Por qué se acepta esto como respuesta, arroja un nullref porque GetValue () devuelve nulo si el objetivo no se ha instanciado aún, lo que dará lugar a una excepción de una línea a continuación r. –

1

obtener las propiedades Nest por ejemplo, Developer.Project.Name

private static System.Reflection.PropertyInfo GetProperty(object t, string PropertName) 
      { 
       if (t.GetType().GetProperties().Count(p => p.Name == PropertName.Split('.')[0]) == 0) 
        throw new ArgumentNullException(string.Format("Property {0}, is not exists in object {1}", PropertName, t.ToString())); 
       if (PropertName.Split('.').Length == 1) 
        return t.GetType().GetProperty(PropertName); 
       else 
        return GetProperty(t.GetType().GetProperty(PropertName.Split('.')[0]).GetValue(t, null), PropertName.Split('.')[1]); 
      } 
+0

Esta solución tiene un defecto importante, no funcionará con listas genéricas. Por ejemplo, usted proporciona FirstObject.MyList [0] .MyValue simplemente se bloqueará porque ignora la [0] primera instancia –

Cuestiones relacionadas