试图在我的代码隐藏文件中找到无限循环的正确方法
本文关键字:无限循环 方法 我的 代码 隐藏文件 | 更新日期: 2023-09-27 18:14:59
我正在尝试在我正在使用的项目的主内容页的c#代码后面部分依次旋转一系列编号的图片。我试着从1开始,移动到5,然后再开始这个过程。这是我目前得到的。它不能工作,因为您需要在if
部分中附加条件。
int i = 1;
restart:
while (i < 6)
{
Image1.ImageUrl = "~/Images/" + i.ToString() + ".png";
i++;
if (i == 5)
{
restart;
}
}
编辑:在尝试将"GOTO"添加到标签后,我无法加载页面。下面是文件的其余部分:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Clark
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetImageURL(); // To ensure image loads on page load
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
SetImageURL(); // Refactored from previous logic
}
private void SetImageURL()
{
// The random function will choose between 1&5 which
// correspond to images 1 through 5
//Random _rand = new Random();
//int i = _rand.Next(1, 5);
//Image1.ImageUrl = "~/Images/" + i.ToString() + ".png";
int i = 1;
restart:
while (i < 6)
{
Image1.ImageUrl = "~/Images/" + i.ToString() + ".png";
i++;
if (i == 5)
{
restart;
}
}
/*
while (true)
{
int i = 1;
do
{
Image1.ImageUrl = "~/Images/" + i.ToString() + ".png";
i++;
} while (i < 6);
} */
}
}
}
使用嵌套循环。
do
{
for (int i = 1; i < 6; i++;
{
Image1.ImageUrl = "~/Images/" + i.ToString() + ".png";
}
}
while (/* additional conditions */)
我选择了do
/while
架构,因为它可以最好地映射到您已经拥有的架构,但是仅仅是一个普通的while
也可以做到这一点。
尽管如此,请记住,除非这只是一个例子,否则这是一个相当愚蠢的事情。当你在这个循环中,你的ImageUrl
不会被读取,所以你可以计算出实际的结果,而不必浪费时间和资源来运行可能会变成这样的无限循环。
这个问题已经演变了。
不使用循环,存储一个应用程序变量:
object imageIndexObj = Application["imageIndex"];
int imageIndex;
if(imageIndexObj == null)
imageIndex = 1;
else
imageIndex = (int)imageIndexObj;
Image1.ImageUrl = "~/Images/" + (imageIndex % 5) + ".png";
Application["imageIndex"] = imageIndex + 1;
这里有一些暗示,特别是在处理多服务器场时。但这对你来说已经足够了。如果你遇到需要多个服务器的用户负载,那么使用这样的工作流可能会变得无关紧要,因为结果将更加随机。
如果您希望五个图像在每个会话而不是每个请求中循环,您也可以在这里使用Session
来代替Application
。那是你的决定。除了这些代码是一样的