如果我在类中重写Tostring()方法;如何在C#中调用预定义的tostring方法将int转换为字符串? [关闭]

问题描述 投票:-2回答:1

Reena必须为她的4年级学生讲授关于世界各地进行的各种体育和游戏的课程。

[为了使班级具有互动性,她决定给每位学生打电话,并询问他们所知道的游戏的名称,玩游戏所需的玩家数量以及有关有时间限制玩的游戏。

通过编写一个C#程序来帮助她,该程序会提示用户输入上述详细信息并将其显示在控制台上。

创建类,以及如下所述的指定成员。

  1. class Game //描述游戏属性的父类

包括游戏名称和最大玩家数量的自动实现属性。

属性名称

说明

公共字符串名称

存储游戏名称的属性。

public int MaxNumPlayers

该游戏包含的最大玩家数量

方法名称

说明

ToString()

应该重写Object类的ToString()方法,并返回一个字符串,其中包含游戏的名称以及示例输出中给出的玩家人数。

  1. class GameWithTimeLimit //应该继承Game类的子类

为分钟生成自动实现的整数属性,以分钟为单位存储游戏的时间限制。

属性名称

说明

Public int TimeLimit

以分钟为单位存储游戏的时限。

方法名称

说明

ToString()

应重写Object类的ToString()方法并返回一个字符串。

应调用父父类ToString并打印播放器的名称和数量。另外,此方法应打印游戏的时间限制。

(请参阅示例输出。]

  1. 班级计划

使用Main方法创建一个名为Program的类,以实例化上述类的对象并显示示例中给出的输出。

注意:

不创建任何新的名称空间。

使用公共访问说明符创建类。

Main方法应在公共类Program中定义。

样本输入:进入游戏蟋蟀输入最大玩家数11输入有时间限制的游戏足球输入最大玩家数11输入时间限制(以分钟为单位)90样本输出:板球的最大玩家数量为11足球的最大人数为11足球时限为90分钟

代码:

using System;

public class Game
{

    public string Name{ get; set; }
    public int MaxNumPlayers {get; set;}

    public override string ToString()
    {
        string str;
        str = "Maximum number of players for "+ Name+" is "+ MaxNumPlayers.ToString();
        return str;
    }


}

public class GameWithTimeLimit : Game
{
    public int TimeLimit
    {
        get; set;
    }
    public override string ToString()
    {
        string str,temp;
        // I want to convert TimeLimit to string 
        //Console.WriteLine(base.ToString());
        str =  base.ToString() + "\nTime Limit for " + Name + " is " + TimeLimit + " minutes" ;
        return str;
    }
}
public class Program
{
    public static void Main(string[] args)
    {
        Game g = new Game();
        GameWithTimeLimit G = new GameWithTimeLimit();
        Console.WriteLine("Enter a game");
        g.Name = Console.ReadLine();
        Console.WriteLine("Enter the maximun number of players");
        g.MaxNumPlayers = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter a game that has time limit");
        G.Name = Console.ReadLine();
        Console.WriteLine("Enter the Maximum number of players");
        G.MaxNumPlayers = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the time limit in minutes");
        G.TimeLimit = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(g.ToString());
        Console.WriteLine(G.ToString());
    }
}
c# tostring
1个回答
0
投票
尝试将ToString()添加到TimeLimit。
© www.soinside.com 2019 - 2024. All rights reserved.