我生成六个数字,将它们添加到一个数组并在标签中显示它们,在我尝试对整数进行排序然后再次显示它们之后,所有这些数字都返回值" 0"
int[] generatedNums = new int[6]; //Array containing generated integers
protected void BtnGenerate_Click(object sender, EventArgs e)
{
Random newRandom = new Random();
for (int i = 0; i < 5; i++)
{
generatedNums[i] = newRandom.Next(1, 50);
}
lblNum1.Text = generatedNums[0].ToString();
lblNum2.Text = generatedNums[1].ToString();
lblNum3.Text = generatedNums[2].ToString();
lblNum4.Text = generatedNums[3].ToString();
lblNum5.Text = generatedNums[4].ToString();
lblNum6.Text = generatedNums[5].ToString();
}
protected void BtnSort_Click(object sender, EventArgs e)
{
Array.Sort(generatedNums);
lblNum1.Text = generatedNums[0].ToString();
lblNum2.Text = generatedNums[1].ToString();
lblNum3.Text = generatedNums[2].ToString();
lblNum4.Text = generatedNums[3].ToString();
lblNum5.Text = generatedNums[4].ToString();
lblNum6.Text = generatedNums[5].ToString();
}
我将两种方法合并为一种,它可以正常工作,有什么帮助吗?
答案 0 :(得分:2)
您的问题是您忘记了Web服务器没有在请求之间保留generatedNums
数组的状态。与大多数Web框架一样,Web窗体是无状态的。当您尝试对数组进行排序时,您需要重新生成列表或从标签中读取它。您的班级成员不会在请求之间保留。
答案 1 :(得分:0)
您只需初始化值0 - 4
(function($) {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//Detect a mouse down. Set the xy coordinates
var mouseDown = false;
$(canvas).mousedown(function(e) {
mouseDown = true;
var bounds = e.target.getBoundingClientRect()
mouseScaleX = e.target.width / bounds.width;
mouseScaleY = e.target.height / bounds.height;
context.beginPath();
context.moveTo(e.offsetX * mouseScaleX, e.offsetY * mouseScaleY);
});
//Detect that the mouse is moving and draw the line while the mouse is still down
$(canvas).mousemove(function(e) {
if (mouseDown) {
var bounds = e.target.getBoundingClientRect()
mouseScaleX = e.target.width / bounds.width;
mouseScaleY = e.target.height / bounds.height;
var x = e.offsetX * mouseScaleX;
var y = e.offsetY * mouseScaleY;
context.lineTo(x, y);
context.strokeStyle = '#000';
context.stroke();
}
});
//On mouse up, reset the coordinates
$(canvas).mouseup(function() {
mouseDown = false;
context.closePath();
});
})(jQuery);
但显示0 - 5
#canvas {
width: 400px;
height: 400px;
border: 1px solid;
margin: 0 auto;
display: block;
}
如果您展示声明generatedNums
,它也会有所帮助答案 2 :(得分:0)
啊,这是一个Web服务器是一个非常重要的细节 并且你可以保持变量不像这样清除
private int[] generatedNums
{
get { return (int[])HttpContext.Current.Session["generatedNums"]; }
set { HttpContext.Current.Session["generatedNums"] = value; }
}
在您的构造函数或初始值设定项中,您可以添加此
if (generatedNums == null)
generatedNums = new int[6];
或更好,你可以在启动服务器时设置它