gpt4 book ai didi

c# - 我不能从另一个类调用公共(public)方法

转载 作者:行者123 更新时间:2023-11-30 14:12:32 24 4
gpt4 key购买 nike

这是有方法的类

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();

关于c# - 我不能从另一个类调用公共(public)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17250272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com