gpt4 book ai didi

在另一个类中发送的 c# 数组发回零

转载 作者:太空宇宙 更新时间:2023-11-03 23:17:51 25 4
gpt4 key购买 nike

我正在解决一个我最近遇到的问题。我只是想运行一个程序来实例化并显示一个我命名为 HockeyPlayer 的对象。我尝试使用它,数组大小为 20。到目前为止,我所做的一切似乎都在起作用。但是,当我编译并完成输入播放器数据时,列表返回为零。我不太确定这里发生了什么。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace TestHockeyPlayer
{
class Program
{
static void Main(string[] args)
{
HockeyPlayer[] players = new HockeyPlayer[20];
int x;
string lastName;
int jerseyNumber;
int goalsScored;

for(x = 0; x < players.Length; ++x)
{
GetPlayerData(out lastName, out jerseyNumber, out goalsScored);
players[x] = new HockeyPlayer(lastName, jerseyNumber, goalsScored);
}

for(x = 0; x < players.Length; ++x)
{
DisplayRoster(players[x]);
}


}

static void DisplayRoster(HockeyPlayer ply)
{
WriteLine("{0, 5}{1, -10}{2, 6}", ply.LastName, ply.JerseyNum, ply.Goals);
}

static void GetPlayerData(out string lastName, out int jerseyNumber, out int goalsScored)
{
string userInput;
WriteLine("Please enter player's last name >>");
lastName = ReadLine();
WriteLine("Please enter the jersey number for {0} >>", lastName);
userInput = ReadLine();
int.TryParse(userInput, out jerseyNumber);
WriteLine("How many goals has {0} scored? >>", lastName);
userInput = ReadLine();
int.TryParse(userInput, out goalsScored);
}
}

class HockeyPlayer
{
private string name;
private int jerseyNum;
private int goals;

public string LastName {get; set;}

public int JerseyNum {get; set;}

public int Goals {get; set;}

public HockeyPlayer(string lastName, int jerseyNumber, int goalsScored)
{
name = lastName;
jerseyNum = jerseyNumber;
goals = goalsScored;
}
}
}

最佳答案

您在 HockeyPlayer 类的构造函数中设置了您的私有(private)字段,但您尝试通过您从未设置过的公共(public)属性检索它们。

将您的属性定义更改为:

public string LastName { get { 返回名称; } set { name = value;} }

等等..

关于在另一个类中发送的 c# 数组发回零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36659504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com