簡體   English   中英

在C#類中使用通用方法

[英]Using a generic method in a C# class

這是我當前的代碼:

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時,它們會顯示在代碼的底部。

您正試圖在一個intdouble值數組中搜索一個string 因此,您對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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM