在C#类中使用泛型方法

时间:2017-11-29 23:34:54

标签: c#

这是我目前的代码:

namespace WindowsFormsApp1
{
public partial class Form1 : Form 
{
    public Random random = new Random();
    public int[] randomInt = new int[20];
    public double[] randomDouble = new double[20];

    public string searchKey;
    public int intOrDouble; // 0 if int, 1 if double

    public static int Search<T>(T[] inputArray, T key) where T : IComparable<T>
    {
        for (int i = 0; i < 20; i++)
        {
            if (inputArray[i].CompareTo(key) == 0)
            {
                return i;
            }
        }
        return -1;
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void randomIntGeneration_Click(object sender, EventArgs e)
    {
        randomNumbersTextBox.Clear(); // empty the textbox
        intOrDouble = 0; // this is for knowing which parameter to send to search method

        // generate 20 random integers and display them in the textbox
        for (int i = 0; i < 20; ++i)
        {
            randomInt[i] = random.Next(0, 100);
            randomNumbersTextBox.Text += randomInt[i].ToString() + "   ";
        }
    }

    private void randomDoubleGenerator_Click(object sender, EventArgs e)
    {
        randomNumbersTextBox.Clear(); // empty the textbox
        intOrDouble = 1; // this is for knowing which parameter to send to search method

        // generate 20 random doubles and display them in the textbox
        for (int i = 0; i < 20; ++i)
        {
            randomDouble[i] = random.NextDouble() + random.Next(0, 100);
            randomNumbersTextBox.Text += randomDouble[i].ToString() + "   ";
        }
    }

    private void searchArrayButton_Click(object sender, EventArgs e)
    {
        searchKey = searchKeyTextBox.Text;
        if(intOrDouble == 0) // int array passed
        {
            resultsTextBox.Text = Search(randomInt, searchKey).ToString();
        }
        else
        {
            resultsTextBox.Text = Search(randomDouble, searchKey).ToString();
        }
    }
}

}

我想要做的是使用这种通用方法。 GUI允许用户生成int或double的随机数组。然后我想在searchArrayButton_Click控件中使用Search方法来显示输入的“searchKey”值是否在数组中。我得到的错误是“方法的类型参数'Form1.Search(T [],T)'无法从用法中推断出来。请尝试明确指定类型参数。”当我尝试在searchArrayButton_Click控件中调用Search两次时,它们出现在代码的底部。

1 个答案:

答案 0 :(得分:0)

您正在尝试为int搜索doublestring值的数组。因此,您对Search的调用有两个不同类型的参数。这与功能签名不匹配。

您需要将该文本框中的任何内容转换为您要搜索的值,无论是int还是double。

if(intOrDouble == 0) // int array passed
{
    resultsTextBox.Text = Search(randomInt, int.Parse(searchKey)).ToString();
}
else
{
    resultsTextBox.Text = Search(randomDouble, double.Parse(searchKey)).ToString();
}