for循环中的数组分配默认会话值

时间:2013-12-13 09:48:32

标签: c# asp.net arrays

在每个循环中,我想要数组serRefine的默认值,但它需要旧的serRefine [4]值

for (int i = 0; i < rptSize.Items.Count; i++)
{
     Label lblSizeCount = (Label)rptSize.Items[i].FindControl("lblSizeCount");
     HiddenField hfSizeID = (HiddenField)rptSize.Items[i].FindControl("hfSizeID");

     string[] serRefine = (string[])Session["RefineSelection"];
     if (serRefine[4].ToString() != "")
     {
         string Finalsids = "";
         string[] sids = serRefine[4].Split(',');
         for (int j = 0; j < sids.Length; j++)
         {
             if (sids[j].ToString() != hfSizeID.Value)
                 Finalsids += sids[j].ToString() + ",";
         }
         Finalsids += hfSizeID.Value;

         Finalsids = Finalsids.TrimEnd(',');
         serRefine[4] = Finalsids;
     }
     else
         serRefine[4] = hfSizeID.Value;

     lblSizeCount.Text = CommonManager.GetProductCountWithAll(serRefine);
}

1 个答案:

答案 0 :(得分:0)

现在我已经理解了这个问题。您希望数组在每次迭代时都处于初始状态。但事实并非如此,因为它是一个引用类型,你在循环中修改它。以下是重现此行为的简化示例:

string[] RefineSelection = new[] {"A", "B", "C", "D", "E" };
for (int i = 1; i <= 3; i++)
{
    string[] serRefine = RefineSelection;  // you're not creating a copy but you're referencing the session-array
    string hfSizeID = "foo" + i;
    Console.WriteLine(string.Join(",", RefineSelection));
    serRefine[4] = hfSizeID;
    Console.WriteLine(string.Join(",", RefineSelection));
}

输出将是:

A,B,C,D,E
A,B,C,D,foo0
A,B,C,D,foo0
A,B,C,D,foo1
A,B,C,D,foo1
A,B,C,D,foo2

因此,在更改之前将使用上次迭代的“foo”值。如上所述,因为数组是引用类型而变量的范围不是循环本身,因此使用相同的引用。

您可以从Session数组创建克隆:

for (int i = 0; i < rep.Count; i++)
{
    string[] copy = (string[])RefineSelection.Clone();
    string hfSizeID = "foo" + i;
    Console.WriteLine(string.Join(",", copy));
    copy[4] = hfSizeID;
    Console.WriteLine(string.Join(",", copy));
}

输出:

A,B,C,D,E
A,B,C,D,foo0
A,B,C,D,E
A,B,C,D,foo1
A,B,C,D,E
A,B,C,D,foo2