首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >字符串表列表( c# )

字符串表列表( c# )
EN

Stack Overflow用户
提问于 2015-06-18 14:09:56
回答 5查看 899关注 0票数 2

我的c#脚本有问题。我想创建一个字符串表的列表如下:

代码语言:javascript
复制
public List<string[]> Signals = new List<string[]>(); 
public string[] Communication  =  new string[3];

所以应该是这样的,我的列表中应该有几个通信实例: Signals = (Communication1,Communication2,.)每个通信都有3个字符串字段。

当我收集了我的3个通信数据(每个通信都不同):

代码语言:javascript
复制
Communication[0]=CommunicationType;
Communication[1]=CommunicationTime;
Communication[2]=CommunicationName;

我把它们储存在我的单子里:

代码语言:javascript
复制
Signals.Add(Communication); // I have also tried .Insert with different Indexes

当我多次这样做时,存储了6个不同的通信表,我希望最后看到每个通信实例,因此我这样做如下:

代码语言:javascript
复制
foreach (string[] Signal in Signals)
{
    foreach (string CommunicationUnit in Signal)
    {
        Print(CommunicationUnit);
    }
}

我所能看到的输出是列表中最后输入的元素的6倍,如下所示

ARINC3 121 Comm6 ARINC3 121 Comm6 ARINC3 121 Comm6 ARINC3 121 Comm6 ARINC3 121 Comm6 ARINC3 121 Comm6

当我想看到列表中的每个元素时,实际上是6个不同的字符串表。

我不明白我的剧本有什么问题。我想错误就在前额循环的某个地方。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2015-06-18 14:17:02

重新创建一个简单的示例:(当您在插入后实例化一个新的字符串数组时,它可以工作)

代码语言:javascript
复制
List<string[]> Signals = new List<string[]>(); 
string[] Communication  =  new string[3];

Communication[0] = "a";
Communication[1] = "b";
Communication[2] = "c";

Signals.Add(Communication);

Communication = new string[3];

Communication[0] = "d";
Communication[1] = "e";
Communication[2] = "f";

Signals.Add(Communication);

foreach (string[] Signal in Signals)
{
    foreach (string CommunicationUnit in Signal)
    {
        Console.WriteLine(CommunicationUnit);
    }
}
票数 3
EN

Stack Overflow用户

发布于 2015-06-18 14:21:30

您似乎只是在列表中添加了6次相同的Communication。

如果将对象存储在列表中,则只需存储对其的引用,而不是副本。

然后,如果您将第一个通信项添加到列表中,然后修改它并再次添加它,那么内存中只有2次对同一个对象的相同引用。

这意味着,如果您更新了您的通信项,您将只更新列表中的所有引用。

必须为每个通信项创建一个新的通信项。

代码语言:javascript
复制
Signals.Add(new string[3] {
    CommunicationType,
    CommunicationTime,
    CommunicationName
});
Signals.Add(new string[3] {
    CommunicationType2,
    CommunicationTime2,
    CommunicationName2
});

代码语言:javascript
复制
string[] Communication  =  new string[3];
Communication[0]=CommunicationType;
Communication[1]=CommunicationTime;
Communication[2]=CommunicationName;
Signals.Add(Communication);
string[] Communication2  =  new string[3];
Communication2[0]=CommunicationType;
Communication2[1]=CommunicationTime;
Communication2[2]=CommunicationName;
Signals.Add(Communication2);

如果使用相同的对象,则只需覆盖其数据。

票数 2
EN

Stack Overflow用户

发布于 2015-06-18 14:16:20

输出是正确的:前3行输出是您的第一个表(或Signals.First())

代码语言:javascript
复制
ARINC3 <- CommunicationType
121us  <- CommunicationTime
Comm6  <- CommunicationName

就像你把它们放在桌子上一样。你有6张表x3行,所以18行。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30917736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档