我尝试生成16位代码,当我添加记录时,所有数字都相同,我该如何解决?
循环中的代码[i] = Newcode;当代码添加到列表中时,代码是核心,将最后一个代码更改为新代码,因此所有代码都与上一次生成相同!!!!
public ActionResult Gen5Rm(GenerateCodeModel model){
Code Newcode = new Code();
int X = Convert.ToInt32(model.Quntity);
Code[] code = new Code[X];
for (int i = 0; i < X; i++)
{
string strDate = "";
string strmonth = "";
string strday = "";
string myday = "";
strmonth = DateTime.Now.ToString("MM");
myday = DateTime.Now.DayOfWeek.ToString();
if (myday == "Sunday")
{
strday = "SU";
}
if (myday == "Monday")
{
strday = "MO";
}
if (myday == "Tuesday")
{
strday = "TU";
}
if (myday == "Wednesday")
{
strday = "WE";
}
if (myday == "Thursday")
{
strday = "TU";
}
if (myday == "Friday")
{
strday = "FR";
}
if (myday == "Saturday")
{
strday = "ST";
}
strDate = generateBarcode();
Newcode.codebase = model.Agent + strmonth +
model.Type_Code + strDate + strday + "5" + model.Dealercode;
Newcode.price = 5;
Newcode.serial = "S" + DateTime.Now.ToString("mmssfff");
code[i] = Newcode;
}
return PartialView("_return5rm", code);
}
public ActionResult Gen5Rm(GenerateCodeModel model){
Code Newcode = new Code();
int X = Convert.ToInt32(model.Quntity);
Code[] code = new Code[X];
for (int i = 0; i < X; i++)
{
string strDate = "";
string strmonth = "";
string strday = "";
string myday = "";
strmonth = DateTime.Now.ToString("MM");
myday = DateTime.Now.DayOfWeek.ToString();
if (myday == "Sunday")
{
strday = "SU";
}
if (myday == "Monday")
{
strday = "MO";
}
if (myday == "Tuesday")
{
strday = "TU";
}
if (myday == "Wednesday")
{
strday = "WE";
}
if (myday == "Thursday")
{
strday = "TU";
}
if (myday == "Friday")
{
strday = "FR";
}
if (myday == "Saturday")
{
strday = "ST";
}
strDate = generateBarcode();
Newcode.codebase = model.Agent + strmonth +
model.Type_Code + strDate + strday + "5" + model.Dealercode;
Newcode.price = 5;
Newcode.serial = "S" + DateTime.Now.ToString("mmssfff");
code[i] = Newcode;
}
return PartialView("_return5rm", code);
}
答案 0 :(得分:0)
Newcode应该在for循环中,否则数组中的所有项都将指向同一个对象(相同的内存地址)
for (int i = 0; i < X; i++)
{
Code Newcode = new Code();
...
}