简体   繁体   中英

Assigning objects to an array C#

Struggling to assign objects to an array in C#.

The output of the code is unexpected because I get the nameOfProject.ClassName(?) x3 rather than name and life points of 3 monsters i added using my for loop. Debug suggests monsters aren't being assigned. Is there a logical flaw that people like me should be looking out for?

class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}
class Program
{
    static void Main(string[] args)
    {
        Monsters[] monster = new Monsters[3];

        for (int i = 0; i < monster.Length; i++)
        {
            Console.WriteLine("Please enter a name");
            string name = Console.ReadLine();
            Console.WriteLine("Please enter life points");
            int points = Convert.ToInt32(Console.ReadLine());
            monster[i] = new Monsters(name,points);
            Console.Clear();
        }
        foreach (var element in monster)
        {
            Console.WriteLine(element);
        }
        Console.ReadKey();

    }

Assignment works just fine. The problem is that you never asign the monster's name and points to a field or property:

class Monsters
{
    public Monsters(string name, int points)
    {
        var monsterName = name;
        var monsterLifePoints = points;
    }
}

This code just assigns the input to local values and then discards them.

Your class should look like this:

class Monsters
{
    public string Name {get;set;}
    public int Points {get;set;}
    public Monsters(string name, int points)
    {
        Name = name;
        Points = points;
    }
}

This line still won't print the details :

Console.WriteLine(element);

You need to either create a string from the properties :

Console.WriteLine($"{element.Name} {element.Points}");

Or override the ToString() method of your class :

 public override string ToString()
{
    return $"{element.Name} {element.Points}";
}

How should WriteLine know that you want to print those two properties and not eg the type-name (which it does per default) or any other wierd string? You have to tell your program how to do this. This is done by overriding ToString

class Monster
{
    public override string ToString() {
        return this.name + " " + this.lifePoints;
    }
}

Furthermore your variables need to be fields:

class Monster
{
    private readonly string name;
    private readonly int lifePoints;

    Monster(string name, int points)
    {
        this.name = name;
        this.lifePoints = points;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM