c# - 编写一个 C# 程序,提示用户输入上述详细信息并将其显示在控制台上
问题描述
编写一个 C# 程序,提示用户输入上述详细信息并将其显示在控制台上。
创建类以及指定的成员,如下所述。
问题:
以下问题的代码未运行。我能得到一些帮助吗?错误即将出现错误 CS0122:“Game.game_name”由于其保护级别而无法访问。
我的代码:
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a game");
string game_name = Console.ReadLine();
Console.WriteLine("Enter the maximum number of players");
int max_players = Convert.ToInt32(Console.ReadLine());
Game game = new Game();
game.GameName = game_name;
game.MaxNumPlayers = max_players;
Console.WriteLine("Enter a game that has time limit");
game_name = Console.ReadLine();
Console.WriteLine("Enter the maximum number of players");
max_players = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter time limit in minutes");
int time_limit = Convert.ToInt32(Console.ReadLine());
GameWithTimeLimit time_game = new GameWithTimeLimit();
time_game.GameName = game_name;
time_game.MaxNumPlayers = max_players;
time_game.TimeLimit = time_limit;
Console.WriteLine(game);
Console.WriteLine(time_game);
}
}
class Game
{
string game_name;
int max_players;
public string GameName
{
set
{
this.game_name = value;
}
}
public int MaxNumPlayers
{
set
{
this.max_players = value;
}
}
public override string ToString()
{
return "Maximum number of players for " + game_name + " is " + max_players;
}
}
class GameWithTimeLimit : Game
{
int time_limit;
public int TimeLimit
{
set
{
this.time_limit = value;
}
}
public override string ToString()
{
Console.WriteLine(base.ToString());
return "Time Limit for " + base.game_name + " is " + this.time_limit + " minutes";
}
}
解决方案
在 C# 中,当没有为类成员提供访问修饰符时,它默认为private。有关访问修饰符及其默认值的描述,请参阅文档。
不能从子类访问成员private
。这就是为什么在您的类中,您尝试访问会引发错误:是私有成员,因此无法从子类访问。GameWithTimeLimit
base.game_name
game_name
GameWithTimeLimit
如果你想对外部调用者隐藏 GameName 但在子类中使用它,你应该使用protected
访问修饰符。但是由于您的GameName
财产上已经有一个公共 setter,因此也可以添加一个公共 getter:
public string GameName
{
get
{
return this.game_name;
}
set
{
this.game_name = value;
}
}
然后你可以在你的子类和其他类中使用它:
public override string ToString()
{
Console.WriteLine(base.ToString());
return "Time Limit for " + this.GameName + " is " + this.time_limit + " minutes";
}
推荐阅读
- java - 在运行时在android中更改所有屏幕方向
- loopbackjs - lb3app 中的 socket.io 安装在 lb4 中的应用程序(环回)
- fullcalendar - Fullcalendar 4:如何在 fullcalendar 上获取已删除事件的元素引用?
- c# - 如何在 Angular 和 C# 中编写 post 方法?
- asynchronous - Flutter 动态标签栏渲染(异步)
- java - 在注入的类中注入一个接口的不同实现
- angular - 角度导航到具有多个参数的路由
- android - 如何在 Window 上获得正确的可用尺寸(没有所有装饰元素)?
- bash - 遍历行并检查特定值
- ruby - Coinbase Pro API “无效签名” RUBY