可以转换为'int'的类型的对象是必需的

时间:2014-03-18 12:33:09

标签: c# string int implicit-conversion

这是我的代码:

namespace Cinemaseats

 {public partial class MainForm : Form
    {
    private const int numOfSeats = 60;
    private int numOfReservedSeats = 0;
    Seat currentSeat = new Seat();
    public MainForm()
    {
        InitializeComponent();
        InitializeGUI();
    }

    private void InitializeGUI()
    {
        radioButton1.Checked = true;
        namn.Text = string.Empty;
        pris.Text = string.Empty;
    }
    private void button1_Click(object sender, EventArgs e)
    {
        **int seatNr = ReadAndValidateSeatNr();**

        if (seatNr < 0)
        {
            MessageBox.Show("Välj ett föremål från listan");
            return;
        }

        if (radioButton2.Checked)
            ReserveSeat(seatNr);
        else
            CancelSeat(seatNr);

        UpdateGUI(seatNr);
    }

    public int GetnumOfSeats()
    {
        return numOfSeats;
    }

    **public int ReadAndValidateSeatNr()
    {
     thelist.Items.Add(test); //test
     return;
    }
    string test = Convert.ToString(2);
}**
}

我已经转换了我的字符串&#34; test&#34;到一个int,但仍然VS说返回值必须是一个int?我希望在我的列表框中显示60和34个座位,也就是说#34;座位1和#34;,#34;座位2和#34;等等。我写了一个测试字符串,看看我是否可以使它工作。我不确定getter和setter方法是如何工作的但是我觉得我在这里需要它们吗?

3 个答案:

答案 0 :(得分:4)

ReadAndValidateSeatNr()函数中,您没有返回任何内容:

public int ReadAndValidateSeatNr()
{
     thelist.Items.Add(test); //test
     return;  //<--------- here nothing is being returned
}

我的编译器给了我同样的错误:P

enter image description here

如果您不需要返回任何内容,请将更改返回void

public void ReadAndValidateSeatNr()
{
     thelist.Items.Add(test); //test
     //return; redundant statement - not even required in this case
}

如果您的要求类似于"Seat 1"等的1,请转到枚举:

enum my_enum{ Seat1=1, Seat2= 2};

public int ReadAndValidateSeatNr()
{
        switch(test)
        {
             case "Seat 1":
             thelist.Items.Add(test); //test
             return (int)my_enum.Seat1;

             case "Seat 2":
             thelist.Items.Add(test); //test
             return (int)my_enum.Seat2;
        }
}

答案 1 :(得分:0)

如果您不想在ReadAndValidateSeatNr方法中返回某些内容,则应更改为:

public void ReadAndValidateSeatNr() 
{
    thelist.Items.Add(test);
}

答案 2 :(得分:0)

方法可以返回int或字符串(也就是说只返回一种类型)。正如其他人所建议的那样,如果您不想返回任何内容,请将返回类型更改为void。

如果您的问题仅在开头有“Seat”字符串,则不应将该项添加到方法内的列表框中。而是从方法返回一个int,并通过在主块中执行类似的操作将项添加到列表框中。

thelist.Items.Add(“Seat”+ ReadAndValidateSeatNr()。ToString());

在这种情况下,您的方法将重新调整int并可以单独使用,您仍然可以以您想要的格式添加到列表框中。

相关问题