带条件的 C# 复制结构

本文关键字:复制 结构 条件 | 更新日期: 2023-09-27 18:34:05

我有一个结构,其中包含一些值strucPos [] poss; 我需要更改它,所以我创建了相同的结构structPos[] strpos = poss;并对其进行一些更改。然后我尝试将 strpos 复制到 poss,但有一个错误:object reference not set to an instance of an object.

poss = null;
while (l < strpos.Length)
{
     if (strpos[l].use != "-")
     {
         poss[poss.Length - 1].count = strpos[poss.Length - 1].count;
         poss[poss.Length - 1].ei = strpos[poss.Length - 1].ei;
         poss[poss.Length - 1].id_r = strpos[poss.Length - 1].id_r;
         poss[poss.Length - 1].nm_p = strpos[poss.Length - 1].nm_p;
     }
     l++;
}

据我了解,这是因为poss是空的。我应该如何更改我的代码?

带条件的 C# 复制结构

简单的更改

poss = null

if (strpos.Length > 0)
    poss = new structPos[strpos.Length];

在循环中,您可能希望使用"l"而不是"poss"。长度 - 1"。

我会做这样的事情:

if (strpos.Length > 0)
{
    poss = new structPos[strpos.Length];
    while (l < strpos.Length)
    {
        poss[l] = new structPos();
        poss[l].use = strpos[l].use;
        if (strpos[l].use != "-")
        {
             poss[l].count = strpos[l].count;
             poss[l].ei = strpos[l].ei;
             poss[l].id_r = strpos[l].id_r;
             poss[l].nm_p = strpos[l].nm_p;
        }
        l++;
    }
}