【问题标题】:Set and get value of the Nested Class by string without class name通过没有类名的字符串设置和获取嵌套类的值
【发布时间】:2019-04-09 23:49:57
【问题描述】:

我有很多 txt 文件,其中包含很多数据。例如:

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]"

在第一个txt文件中,所有参数的第一个值都是一个线圈数据。第二个值是第二个线圈数据。 我想将所有值放入一个包含所有值的类/对象中`就像你在图片上看到的那样。

当我上传对象时,索引不能滑动,所以如果我从集合中选择索引1,那么我会得到正确的数据。

如你所见,我创建了一个类,我无法通过字符串获取嵌套类属性。

我有下一堂课

    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; }
}

我想设置和获取这样或类似的值:

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);

【问题讨论】:

  • 您是否考虑过使用简单的Dictionary&lt;string,string&gt; 来代替具有属性的嵌套类?
  • @obl 那不是嵌套类。
  • @Fildor 现在该程序可以使用 Dictionary,但它并不是真正动态的。
  • “动态”是什么意思?你能解释一下你在这一切背后的实际目标是什么吗?

标签: c# class reflection properties


【解决方案1】:

看起来您的参数名称已经告诉您Station 是什么,除非我看错了。

parameter1_1 =&gt;第一个数字告诉你Station_{n},第二个数字告诉你cam_term_{n}_val

那么,为什么不按照@Fildor 的建议放弃 Station_1Station_2 类,而只使用 Dictionary&lt;string, int&gt;Dictionary&lt;string, object&gt;(如果您需要存储没有值的密钥)?

反射很昂贵,只有在绝对必要时才应使用。正如您目前所解释的那样,您的情况似乎不需要它。

【讨论】:

  • 是的,在例子中名称相似,但在现实生活中,我想要你的地方我不知道参数名称的站名,因为它是不同的。请检查图片。如果反射很昂贵,那么如何将参数名称链接到站?你能推荐一个好的方法吗?
  • @Alex 请更新您的代码以显示您在文本文件中的阅读方式。我不明白你所说的站名和参数名不同是什么意思。那你怎么知道哪些物业去哪个车站?
猜你喜欢
  • 2012-05-04
  • 2012-05-28
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多