c#复制有条件的结构

时间:2014-12-11 14:53:18

标签: c#

我的结构有一些值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为空。我该如何更改我的代码?

1 个答案:

答案 0 :(得分:2)

简单的改变

poss = null

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

在循环中,你可能想要使用&#34; l&#34;而不是&#34; poss.Length - 1&#34;。

我会做这样的事情:

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