I was researching at a fragment of someone else's code and something seemed curious to me.(just because I'm not familiar with the с# language)
there is an interface with the following method
internal interface IPlayer
{
List<int> MakeMove(List<int> Gameboard, int Player);
}
then a list is created in one of the classes and the interface is used there as a generic
public List<IPlayer> AI_Players = new List<IPlayer> { };
. . .
public void AIMove(int AI_Type)
{
Gameboard = AI_Players[AI_Type].MakeMove(Gameboard, Currentplayer);
}
Can you please explain what is a list with interfaces as a generic?I understand what, for example, a list with an int generic is..but..what does this list store?
and what is [AI_Type] in this line?
Gameboard = AI_Players[AI_Type].MakeMove(Gameboard, Currentplayer);
CodePudding user response:
In short, this means that the list can only contain objects that implement this interface. So the individual elements of the list can be different concrete classes, but each of these classes must implement the interface.
CodePudding user response:
AI_Players[AI_Type]
AI_Type
would be an index. And it might be argued that a better name would be aiPlayerIndex, or that the list should be renamed to aiPlayerTypes;
what does this list store?
It stores references to objects, where the type of reference is IPlayer
Can you please explain what is a list with interfaces as a generic?
Interfaces is a kind of type, just like a int or a string is a type. A list can contain values of any type, int, string, IPlayer or any other type.
Note that the objects in the list might be of a different type than the reference. It is perfectly fine to have a list of IPlayer that contains both objects of AIPlayer and HumanPlayer.