我需要将对象的名称(测试)与已放入队列的测试的名称进行比较.我的逻辑是使用一个foreach循环,这样对于队列中的每个测试,我可以将用户提供的名称与每个测试的名称进行比较,直到找到匹配项(其中它将告诉用户他们所做的分数)在消息框中的测试).
代码段中的代码不完整;使用带有getter的submittedTests不起作用(在intellisense中没有给我一个选项).
这发生在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 --");
}
}