检查队列中对象的属性
本文关键字:属性 对象 队列 检查 | 更新日期: 2023-09-27 18:11:18
我需要将对象(test)的名称与已放入队列中的测试的名称进行比较。我的逻辑是使用foreach循环,这样对于队列中的每个测试,我都可以将用户提供的名称与每个测试中的名称进行比较,直到找到匹配(在此过程中,它将在消息框中告诉用户他们在测试中获得的分数)。
代码片段中的代码不完整;使用带有getter的submittedTests不起作用(在智能意义上没有给我一个这样做的选项)。
这发生在btnFindTest_Click方法中。这是我目前得到的代码:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConsoleApplication1
{
public partial class Form1 : Form
{
//Stack and Queue calls
Queue submittedTest = new Queue();
Stack outForChecking = new Stack();
public Form1()
{
InitializeComponent();
}
private void btnSubmitTest_Click(object sender, EventArgs e)
{
//generates a random test score
Random rdm = new Random();
int testScore = rdm.Next(0, 100);
string score = testScore.ToString();
//assigns user input to a variable
string name = txtName.Text;
//Generate a new test that passes in
Test tests = new Test(name, score);
//shows the user the name they just enetered
label3.Text = String.Format("{0}", name);
//adds submitted test to the queue, then displays that test in a list box
submittedTest.Enqueue(tests);
listSubTests.Items.Add(new Test(name, score));
//Clears input box for next user input
txtName.Clear();
}
private void btnFindTest_Click(object sender, EventArgs e)
{
string compareName = "";
string tempName = txtName.Text;
foreach (Test tests in submittedTest)
{
if (compareName == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}
}
public void txtName_TextChanged(object sender, EventArgs e)
{
}
private void txtScore_TextChanged(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
}
}
测试对象在它自己的类中定义
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Test
{
private string name;
private string score;
public string Name
{
get { return name; }
set { name = value; }
}
public string Score
{
get { return score; }
set { score = value; }
}
public Test(string name, string score)
{
this.name = name;
this.score = score;
}
public override string ToString()
{
return (String.Format("{0} {1} ", name, score));
}
}
}
我对c#比较陌生,这个项目是为了学校,所以如果我离得远,请告诉我!
根据您的示例,您可能已经忘记使用对象:
foreach (Test tests in submittedTest)
{
if (tests.Name == tempName)
{
System.Windows.Forms.MessageBox.Show("Your score was --");
}
}