如何在同一个类中设置属性?

时间:2015-07-16 00:37:59

标签: c# properties

我在设置某些变量的值时遇到了困难。在我的GameController类中,我希望用户输入玩家的数量。然后我希望我的代码创建一个数组,为每个玩家保存分数。

class Program
{
    static void Main(string[] args)
    {
        Game GC = new Game();
        GC.GetNumberPlayers();
        GC.SetInitialScores();
    }               
}

class Game
{
    private int players;
    private int[] scores;
    private string[] playerNames;

    public int Players
    {
        get { return players; }
        set { players = value; ; }
    }

    public int[] Scores
    {
        get { return scores; }
        set { scores = value; }
    }

    public int GetNumberPlayers()
    {
        string playersString;
        Console.WriteLine("Enter number of players");
        playersString = Console.ReadLine();
        Int32.TryParse(playersString, out players);
        return players;
    }

    public int[] SetInitialScores()
    {
        for (int i = 0; i < players; i++ )
        {
            scores[i] = 0;
        }
        return scores;
    }
}

1 个答案:

答案 0 :(得分:1)

一些事情:

GetNumberPlayers返回integer,由于将其称为GC.GetNumberPlayers();

,您没有对其进行任何操作

如果您希望获得GetNumberPlayers()的值,则需要将其称为int numPlayers = GC.GetNumberPlayers();

由于您在try分析中设置了players值,因此您没有任何理由返回它,因为您只在内部使用它(或者如果您在外部使用它,则将其分配给变量为在上面)

对于您的函数SetInitialScores也是如此,还有一个问题。数组需要将它们的长度声明为初始化的一部分。您根本没有初始化数组,因此会遇到运行时错误。您可以根据在播放器中输入的值初始化数组:

public void SetInitialScores()
{
    scores = new int[players];

    for (int i = 0; i < players; i++ )
    {
        scores[i] = 0;
    }
}

这是一个小提琴演示:https://dotnetfiddle.net/JmHsLQ

和完全修改过的代码:

public class Program
{
    public static void Main(string[] args)
    {
        Game GC = new Game();
        var players = GC.GetNumberPlayers();
        var scores = GC.SetInitialScores();

        Console.WriteLine("You entered {0} players!", players);

        Console.WriteLine("Printing scores");
        foreach (int val in scores)
        {
            Console.WriteLine(val);
        }

    }               
}

public class Game
{
    private int players = 0;
    private int[] scores;
    private string[] playerNames;

    public int Players
    {
        get { return players; }
        set { players = value; ; }
    }

    public int[] Scores
    {
        get { return scores; }
        set { scores = value; }
    }

    public int GetNumberPlayers()
    {
        string playersString;
        Console.WriteLine("Enter number of players");
        playersString = Console.ReadLine();
        Int32.TryParse(playersString, out players);
        return players;
    }

    public int[] SetInitialScores()
    {
        scores = new int[players];

        for (int i = 0; i < players; i++ )
        {
            scores[i] = 0;
        }

        return scores;
    }
}