我不能从另一个类调用公共方法

Luk*_*ina 3 c# winforms

这是带方法的类

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要形式

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
  }
}
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息:

错误
1'System.Windows.Forms.Form'不包含'GetGameName'的定义,并且没有扩展方法'GetGameName'接受类型'System.Windows.Forms.Form'的第一个参数可以找到(你错过了吗?使用指令或程序集引用?)

几个星期前我写了类似的代码,它完美无缺.

Zbi*_*iew 6

更换

Form newGame = new NewGame();
Run Code Online (Sandbox Code Playgroud)

NewGame newGame = new NewGame();
Run Code Online (Sandbox Code Playgroud)

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

如果你真的需要使用父类型(Form),你可以将你的对象转换为NewGame:

Form newGame = new NewGame();
string gameName = ((NewGame)newGame).GetGameName();
Run Code Online (Sandbox Code Playgroud)