首页 > 解决方案 > 编写一个 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#

解决方案


在 C# 中,当没有为类成员提供访问修饰符时,它默认为private。有关访问修饰符及其默认值的描述,请参阅文档。

不能从子类访问成员private。这就是为什么在您的类中,您尝试访问会引发错误:是私有成员,因此无法从子类访问。GameWithTimeLimitbase.game_namegame_nameGameWithTimeLimit

如果你想对外部调用者隐藏 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";
    }

推荐阅读