简体   繁体   中英

Set and get value of the Nested Class by string without class name

I have a lot of txt file, that contains a lot of datas. For example:

1.txt
parameter1_1="[1 3 21 12 42]"
parameter2_1="[4 2 28 72 46]"
parameter2_2="[2 6 46 75 76]"
58.txt
parameter1_1="[9 8 98 87 89]"
parameter1_2="[2 4 11 42 62]"
parameter2_1="[9 4 25 67 56]"
parameter2_2="[7 6 87 79 75]"

In the first txt file all of the parameter's first value is a coil datas. The second value is the second coil datas. I want to put all of the value into one class/object what is contains all of the value`like you can see on the picture.

在此处输入图片说明

When I upload the object, the index cannot be slip, so if I choose the index 1 from teh collection, then I get the correct datas.

I created a class as you can see, and I cannot get the nested class property by string.

I have the next class

    public class Coil
{
    public string ID { get; set; }
}

public class FailStation : Coil
{
    public Station_1 Station_1 = new Station_1();
    public Station_2 Station_2 = new Station_2();
}

public class Station_1
{
    public string parameter1_1{ get; set; }
    public string parameter1_2 { get; set; }
}
public class Station_2
{
    public string parameter2_1{ get; set; }
    public string parameter2_2 { get; set; }
}

I would like to set and get the value like this or something simiar:

FailStationcoil coil = new FailStation();
List<FailStation> AllCoil = new List<FailStation>();
coil["parameter1_1"] = "value"; //or
coil.SetPropValue("parameter1_1", "value");
coil["ID"]="1";
AllCoil.Add(coil);

It looks like your parameter names already tell you what Station it is, unless I'm misreading it.

parameter1_1 => the first number tells you Station_{n} , the second number tells you cam_term_{n}_val

So why not ditch the Station_1 and Station_2 classes and just use a Dictionary<string, int> or Dictionary<string, object> (if you need to store the keys with no value) as @Fildor suggested?

Reflection is expensive and should only be used if absolutely necessary. Your situation, as you have explained so far, doesn't look like it requires it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM