【发布时间】:2021-12-15 15:13:49
【问题描述】:
我尝试使用 C# 创建简单的控制台应用程序。我想用这些简单的东西 我的申请。
在我的团队类中有这些方法。
- 成员变量 - teamName(string)
- 成员变量 - noOfPlayers(int)
- 构造函数 1.它接受2个参数,分别分配给teanName和noOfPlayers。
- 成员函数 AddPlayer(count) 1.以整数计数为参数,noOfPlayers按计数递增。
- 成员函数 RemovePlayer 1.它将整数计数作为参数并尝试按计数减少onOfPlayers。 2.如果 decreasign 使 noOfPlayers 为负数,则此函数简单地返回 false 3.Else 减少 noOfPlayers 的数量并返回 true。
在我的 Subteam 类(继承自 Team 类)中有这些方法。
- 构造函数。 1.它需要2个参数teamName和noOfPlayers,并调用基类构造函数 这些参数。
- 成员函数 ChangeTeamName
- 它将字符串名称作为参数并将teamName 更改为名称。
在我的 ChangeTeamName 方法中,我需要使用 name 参数并将名称更改为 teamName。但我不知道该怎么做。请帮我用上述任务创建这个简单的应用程序。并请检查其他代码是否正确。
我在尝试运行程序时遇到这些错误。
1.严重性代码描述项目文件行抑制状态 错误 CS1061“Program.Subteam”不包含“onOfPlayers”的定义,并且找不到接受“Program.Subteam”类型的第一个参数的可访问扩展方法“onOfPlayers”(您是否缺少 using 指令或程序集引用? ) ConsoleApp1 C:\Users\Sandanuwan\Desktop\ConsoleApp1\ConsoleApp1\Program.cs 74 活动
2.严重性代码描述项目文件行抑制状态 错误 CS0122 'Program.Team.noOfPlayers' 由于其保护级别 ConsoleApp1 C:\Users\Sandanuwan\Desktop\ConsoleApp1\ConsoleApp1\Program.cs 68 Active 而无法访问
namespace ConsoleApp1
{
public partial class Program
{
public class Team
{
string teamName;
int noOfPlayers;
public Team(string teamName, int noOfPlayers)
{
this.teamName = teamName;
this.noOfPlayers = noOfPlayers;
}
public void AddPlayer(int count)
{
noOfPlayers = count++;
}
public bool RemovePlayer(int count)
{
noOfPlayers = count--;
if (noOfPlayers < 0)
{
return false;
}
return true;
}
}
class Subteam : Team
{
public Subteam(string teamName, int noOfPlayers) : base(teamName, noOfPlayers)
{
}
public void ChangeTeamName(string name)
{
}
}
static void Main(string[] args)
{
if(!typeof(Subteam).IsSubclassOf(typeof(Team)))
{
throw new Exception("Subteam class chould inherit from Team class");
}
String str = Console.ReadLine();
String[] strArr = str.Split();
string initialName = strArr[0];
int count = Convert.ToInt32(strArr[1]);
Subteam teamObj = new Subteam(initialName, count);
Console.WriteLine("Team " + teamObj.teamName + " created");
str = Console.ReadLine();
count = Convert.ToInt32(str);
Console.WriteLine("Current number of players in team " + teamObj, teamName + " is " + teamObj.noOfPlayers);
teamObj.AddPlayer(count);
Console.WriteLine("New number of players in team " + teamObj.teamName + " is " + teamObj.onOfPlayers);
str = Console.ReadLine();
count = Convert.ToInt32(str);
Console.WriteLine("Current number of players in team " + teamObj.teamName + " is " + teamObj.onOfPlayers);
var res = teamObj.RemovePlayer(count);
if(res)
{
Console.WriteLine("New number of players in team " + teamObj.teamName + " is " + teamObj.onOfPlayers);
} else
{
Console.WriteLine("Number of players in team " + teamObj.teamName + " remains same");
}
str = Console.ReadLine();
teamObj.ChangeTeamName(str);
Console.WriteLine("Team name of team " + initialName + " changed to " + teamObj.teamName);
}
}
}
【问题讨论】:
-
onOfPlayers与noOfPlayers不同 - 请查看前两个字母。