C# 在父类中调用子类的变量
我试图获取父类中存储在子类中的 userInput 变量的值,但我无法访问它,并且每次尝试后我都会遇到很多错误。你能帮我吗?
这是我的代码的一部分:
//Child class
class tictactoe
{
public void beginGame()
{
ConsoleKeyInfo gebruikerInvoer;
gebruikerInvoer = Console.ReadKey();
//Rest of code
}
}
//Parent class
namespace Quizz
{
class Program
{
public static void Main(string[] args)
{
tictactoe minigame1 = new tictactoe();
while (minigame1.gebruikerInvoer)
{
//Rest of code
}
}
}
}
这是我得到的错误
'tictactoe' does not contain a definition for 'gebruikerInvoer' and no accessible extension method 'gebruikerInvoer' accepting a first argument of type 'tictactoe' could be found (are you missing a using directive or an assembly reference?)
我认为我需要创建一个方法从父级调用它,如果是这样:我应该给出什么类型,因为变量是 ConsoleKeyInfo,稍后会转换为字符串?
gebruikerInvoer.KeyChar.ToString()
I am trying to raed the value of userInput variable in my parent class which is stored in my child class, but I can't reach it and I get many errors one after one after each try. Can you please help me?
This is apart of my code:
//Child class
class tictactoe
{
public void beginGame()
{
ConsoleKeyInfo gebruikerInvoer;
gebruikerInvoer = Console.ReadKey();
//Rest of code
}
}
//Parent class
namespace Quizz
{
class Program
{
public static void Main(string[] args)
{
tictactoe minigame1 = new tictactoe();
while (minigame1.gebruikerInvoer)
{
//Rest of code
}
}
}
}
This is the error I get
'tictactoe' does not contain a definition for 'gebruikerInvoer' and no accessible extension method 'gebruikerInvoer' accepting a first argument of type 'tictactoe' could be found (are you missing a using directive or an assembly reference?)
I think that I will need to make a method to call it from the parent, if so: what type should I give since the variable is a ConsoleKeyInfo that is later converted to string?
gebruikerInvoer.KeyChar.ToString()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如注释所表明的,您需要首先使变量对外界可见。局部变量始终对其他类隐藏。因此,让我们首先解决这个问题:
接下来,您需要定义一个语句来测试变量的值,该语句可以返回 true 或 false 语句以使用
while
循环。为了解决这个问题,我们可以这样做:然后,为了逃避 while 循环,您可以使用
return
、break
,或者在某些条件下更改本地bool
代码> minigameRun 为 false。在此代码中,bool
最初是使用?:
运算符分配的。您可以在此处阅读有关其使用的更多信息As the comments have made apparent, you need to first make the variable visible to the outside world. Local variables are always hidden from other classes. So lets fix this first:
Moving on from there you need to define a statement to test the variable's value in a way that can return a true or false statement to use a
while
loop. To fix that we can do something like this:Then to escape the while loop you can use
return
,break
, or upon some condition change the localbool
minigameRun to false. Thebool
is initially assigned in this code using the?:
operator. You can read more about its use here