我需要实现一个搜索按钮,它将我TextBox的值与数组中的值进行比较,如果它们匹配,则返回索引,否则返回-1. 我已经实现了随机数组double以及int所有界面和按钮。这是必须使用的IComparable,CompareTo()但我不知道如何实现它。我尝试实现一个Search方法,但它不起作用,我不知道如何在SearchButton_Click事件处理程序中调用它。
这就是我到目前为止所拥有的:
public partial class MainWindow : Window
{
int[] numb = new int[6];
double[] numb2 = new double[6];
public MainWindow ()
{
InitializeComponent ();
}
//Create Int
private void Button_Click (object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear ();
resultsBox.Items.Add ("Index Value\n");
Random rnd = new Random ();
for (int i = 0; i < 6; i++) {
numb[i] = rnd.Next (0, 999);
string m = i.ToString () + "\t" + numb[i].ToString ();
resultsBox.Items.Add (m);
}
}
//Create Double
private void CreateDouble_Click (object sender, RoutedEventArgs e)
{
resultsBox.Items.Clear ();
resultsBox.Items.Add ("Index Value\n");
Random rnd = new Random ();
for (int i = 0; i < 6; i++) {
numb2[i] = Math.Round (rnd.NextDouble () * (999), 2);
string m = i.ToString () + "\t" + numb2[i].ToString ();
resultsBox.Items.Add (m);
}
}
//Search
private void SearchButton_Click (object sender, RoutedEventArgs e) { }
static int Search<T> (T[] dataArray, T searchKey) where T : IComparable<T>
{
//Iterate through the array.
for (int iter = 0; iter < dataArray.Length; iter++) {
//Check if the element is present in the array.
if (dataArray[iter].CompareTo (searchKey) == 0) {
//Return the index if the element is present in the array.
return iter;
}
}
//Otherwise return the index -1.
return -1;
}
}
谢谢!
