加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 01:55:34 所属栏目:百科 来源:网络整理
导读:这是带方法的类 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() { ret
这是带方法的类

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;
  }
}

这是我的主要形式

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
  }
}

我收到一条错误消息:

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?)

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

解决方法

更换

Form newGame = new NewGame();

NewGame newGame = new NewGame();

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

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

Form newGame = new NewGame();
string gameName = ((NewGame)newGame).GetGameName();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读