3

this is class with methods

public partial class NewGame : Form
{
  public NewGame()
  {
    InitializeComponent();
    this.Icon = new Icon("Resources/iconG.ico");
    comboBoxGenre.Items.AddRange(Enum.GetNames(typeof(Game.Genre)));
  }

  public string GetGameName()
  {
    return txtbxGameName.Text.Trim();
  }

  public int GetGenreSelector()
  {
    return comboBoxGenre.SelectedIndex;
  }
}

this is my main form

private void addGameToolStripMenuItem_Click(object sender, EventArgs e)
{
  Form newGame = new NewGame();
  newGame.ShowDialog(this);
  if (newGame.DialogResult==DialogResult.OK)
  {
    string gameName = newGame.GetGameName(); //this part doesn't work
  }
}

i got a error message:

Error 1
'System.Windows.Forms.Form' does not contain a definition for 'GetGameName' and no extension method 'GetGameName' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?)

few weeks earlier i wrote similar code and it worked flawlessly.

4

3 回答 3

6

代替

Form newGame = new NewGame();

NewGame newGame = new NewGame();

您的newGame变量是 type Form,不包含这些方法。您已经在类中定义了这些方法,因此如果您使用正确的类型NewGame,它们将是可见的。

如果您确实需要使用父类型(Form),您可以将您的对象转换为NewGame

Form newGame = new NewGame();
string gameName = ((NewGame)newGame).GetGameName();
于 2013-06-22T11:35:31.300 回答
1

变量的静态类型newGameForm,因此只有 的方法Form是可见的,即使变量实际上指向一个NewGame对象。使变量的类型与对象的实际类型相匹配,方法就可以访问了。

NewGame newGame = new NewGame();
于 2013-06-22T11:35:43.827 回答
0

尝试这个

用这个替换你的方法

private void addGameToolStripMenuItem_Click(object sender, EventArgs e)
{
  NewGame newGame = new NewGame();
  newGame.ShowDialog(this);
  if (newGame.DialogResult==DialogResult.OK)
  {
    string gameName = newGame.GetGameName(); //this part doesn't work
  }
}
于 2013-06-22T11:44:53.573 回答