简体   繁体   English

通过没有类名称的字符串设置和获取嵌套类的值

[英]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. 我有很多txt文件,其中包含很多数据。 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. 在第一个txt文件中,所有参数的第一个值都是线圈数据。 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. 当我上传对象时,索引不能是滑动的,因此,如果我从集合中选择索引1,那么我将获得正确的数据。

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. 似乎您的参数名称已经告诉您它是什么Station ,除非我误读了它。

parameter1_1 => the first number tells you Station_{n} , the second number tells you cam_term_{n}_val parameter1_1 =>第一个数字告诉您Station_{n} ,第二个数字告诉您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? 那么,为什么不放弃Station_1Station_2类,而只使用@Fildor建议的Dictionary<string, int>Dictionary<string, object> (如果您需要存储没有值的键)呢?

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. 正如您到目前为止所解释的,您的情况似乎并不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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