Utilizzo della riflessione per impostare una proprietà di una proprietà di un oggetto

StackOverflow https://stackoverflow.com/questions/1402479

  •  05-07-2019
  •  | 
  •  

Domanda

Ho due lezioni.

public class Class1 {
   public string value {get;set;}
}

public class Class2 {
   public Class1 myClass1Object {get;set;}
}

Ho un oggetto di tipo Class2. Ho bisogno di usare la riflessione su Class2 per impostare la proprietà value ... vale a dire, se lo facessi senza riflessione, ecco come farei:

Class2 myObject = new Class2();
myObject.myClass1Object.value = "some value";

C'è un modo per fare quanto sopra, mentre si usa la reflection per accedere alla proprietà "myClass1Object.value" ?

Grazie in anticipo.

È stato utile?

Soluzione

Fondamentalmente dividerlo in due accessi alle proprietà. Per prima cosa ottieni la proprietà myClass1Object , quindi imposti la proprietà value sul risultato.

Ovviamente dovrai prendere il formato in cui hai il nome della proprietà e dividerlo, ad es. a punti. Ad esempio, questo dovrebbe avere una profondità arbitraria di proprietà:

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

Certo, probabilmente vorrai un po 'più di controllo degli errori di quello :)

Altri suggerimenti

Stavo cercando risposte al caso in cui ottenere un valore di proprietà, quando viene fornito il nome della proprietà, ma il livello di annidamento della proprietà non è noto.

Eg. se l'input è "valore" invece di fornire un nome di proprietà completo come " myClass1Object.value " ;.

Le tue risposte hanno ispirato la mia soluzione ricorsiva di seguito:

public static object GetPropertyValue(object source, string property)
{
    PropertyInfo prop = source.GetType().GetProperty(property);
    if(prop == null)
    {
      foreach(PropertyInfo propertyMember in source.GetType().GetProperties())
      { 
         object newSource = propertyMember.GetValue(source, null);
         return GetPropertyValue(newSource, property);
      }
    }
    else
    {
       return prop.GetValue(source,null);
    }
    return null;
}
   public static object GetNestedPropertyValue(object source, string property)
    {
        PropertyInfo prop = null;
        string[] props = property.Split('.');

        for (int i = 0; i < props.Length; i++)
        {
            prop = source.GetType().GetProperty(props[i]);
            source = prop.GetValue(source, null);
        }
        return source;
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top