简体   繁体   中英

Trying to make a multiple valued list results in error

I'm trying to make a list that takes 2 parameters in classes Program.cs and Game.cs. In Program.cs I am doing this: (The error is being given under game which is saying: Game does not contain a constructor that takes 2 arguments. List<Game> JoinLists = new List<Game>(); JoinLists.Add(new Game("Elf", 6));

In-Game.cs I have this written:

public class Game
{
    private string _type;
    private int _strength;

    public void JoinLists(string charType, int strength)
    {
        this._type = charType;
        this._strength = strength;
    }
}

Constructors must have same name as the class:

public class Game
{
    private string _type;
    private int _strength;

    public Game(string charType, int strength)
    {
        this._type = charType;
        this._strength = strength;
    }
}

and no return in the signature.

Read more here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

Your error is pretty self explanatory Game does not contain a constructor that takes 2 arguments , it means that you should add the constructor with 2 arguments, obviously

public class Game
{
    private string _type;
    private int _strength;

    public Game(string charType, int strength)
    {
        this._type = charType;
        this._strength = strength;
    }
}

From specs

A constructor is a method whose name is the same as the name of its type. Its method signature includes only the method name and its parameter list; it does not include a return type.

You can also omit this pointer, because your class fields and constructor arguments have the different names, there is no need to qualify them using this

create a constructor

public Game(string charType, int strength)
{
   // code here
}

Or you can change the create Game

List<Game> JoinLists = new List<Game>();
JoinLists.Add(new Game().JoinLists("Elf", 6));

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