简体   繁体   English

接口作为通用参数

[英]interface as generic parameter

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?你能解释一下什么是带有通用接口的列表吗?我明白,例如,带有 int 通用的列表是什么......但是......这个列表存储什么?

and what is [AI_Type] in this line?这一行中的[AI_Type]是什么?

Gameboard = AI_Players[AI_Type].MakeMove(Gameboard, Currentplayer);

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.因此列表中的各个元素可以是不同的具体类,但这些类中的每一个都必须实现该接口。

AI_Players[AI_Type] AI_Players[AI_Type]

AI_Type would be an index . AI_Type将是一个索引 And it might be argued that a better name would be aiPlayerIndex , or that the list should be renamed to aiPlayerTypes ;并且可能有人认为更好的名称是aiPlayerIndex ,或者列表应该重命名为aiPlayerTypes

what does this list store?这个列表存储什么?

It stores references to objects, where the type of reference is IPlayer它存储对对象的引用,其中引用的类型是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.接口是一种类型,就像 int 或字符串是一种类型一样。 A list can contain values of any type, int, string, IPlayer or any other type.列表可以包含任何类型的值,int、string、IPlayer 或任何其他类型。

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 .拥有一个包含AIPlayerHumanPlayer对象的IPlayer列表是非常好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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