ASP.NET使用Application对象实现漂流瓶
最后实现效果
其实也很简单
//扔一个button中代码
protected void Button1_Click(object sender, EventArgs e)
{
//判断是否输入了愿望
if (this.txtmsg.Text == string.Empty)
{
lblmsg.Text = "请输入你的愿望吧!";
}
else
{
//将愿望定义一个集合保存到application中
List<string> bottles = Application["bottles"] as List<string>;
//如果集合为空则创建一个
if (bottles == null)
{
bottles = new List<string>();
//添加初始信息
bottles.Add("什么也没捞到,在捞捞看!");
bottles.Add("哇,好大一只螃蟹");
bottles.Add("哇,好大一只大龙虾");
bottles.Add("哇,捞到一只鲸鱼");
}
//拼接到集合中
bottles.Add("漂流瓶" + this.txtmsg.Text);
//保存到对象中
Application["bottles"] = bottles;
this.txtmsg.Text = "";
this.lblmsg.Text = "你成功扔出了一个漂流瓶";
}
}
//捞捞看button代码
protected void Button2_Click(object sender, EventArgs e)
{
List<string> bottles = Application["bottles"] as List<string>;
//判断集合中是否有值
if (bottles != null)
{
//以当前时间生成随机数
Random rand = new Random(DateTime.Now.Millisecond);
//随机数的最大值为集合中的数量
int num = rand.Next(bottles.Count);
//使用三目运算符判断是否捞到了
this.lblmsg.Text = (num == 0?"":"你捞到了" + bottles[num]);
}
else
{
this.lblmsg.Text = "大海中没有漂流瓶";
}
}
感谢大佬指正 小Monkey
如果你觉得有用的话,就留个赞吧!蟹蟹