mercredi 9 mai 2018

Looping through struct in class with reflection

public struct volt_struct
{
    public string volt1;
    public string volt2;
    public string volt2;
    public string volt3;
}
private class Injection_class
{
    public volt_struct stru1;
    public volt_struct stru2;
    public volt_struct stru3;
    public volt_struct stru4;
    public volt_struct stru5;
    public volt_struct stru6;
}

public void main()
{
    Injection_class Time = new Injection_class();

    //Here is code that fills Time with Time values as string type

    string s="";
    FieldInfo[] fi_inner = Time.stru1.GetType().GetFields();
    FieldInfo[] fi_outer = Time.GetType().GetFields();

    // This part is wrong, but shows what I want to achive.
    foreach(FieldInfo field_outer in fi_outer)
    {
        foreach(FieldInfo field_inner in fi_inner)
        {
            s = string.concat(s+field_outer.field_inner.GetValue(Time) + ";");
        }
    }

}

I want to concatenate the strings stored inside Time into the string s using reflection. Later on I have to modify the class and struct and I don't want to adjust the concatenating code.

I got the results I want with using a foreach loop for each struct inside the class.

 foreach (FieldInfo field in fi_inner)
{
    s = string.Concat(s + field.GetValue(Time.stru1) + ";");
    //field.SetValue(Time, "not measured"); //reset value
}
foreach (FieldInfo field in fi_inner)
{
    s = string.Concat(s + field.GetValue(Time.stru2) + ";");
    //field.SetValue(Time, "not measured"); //reset value
}
//and so one for each other struct

I want to achieve it like in the first example I gave. Is this possible?





Aucun commentaire:

Enregistrer un commentaire