Csharp/C#教程:如何在C#中获取列表中新添加项的索引?分享


如何在C#中获取列表中新添加项的索引?

当我将一个项目(一个类的实例)添加到列表中时,我需要知道新项目的索引。 是否可以使用任何function?

示例代码:

MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY)); 

MapTiles.Count将为您提供将添加到列表中的下一个项目的索引

就像是:

 Console.WriteLine("Adding " + MapTiles.Count + "th item to MapTiles List"); MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY)); 

 Class1 newTile = new Class1(num, x*32 + cameraX, y*32 + cameraY); MapTiles.Add(newTile); int index = MapTiles.IndexOf(newTile); 

在添加之前立即读取Count

 int index = MapTiles.Count; MapTiles.Add(new Class1(num, x * 32 + cameraX, y * 32 + cameraY)); 

如果你总是使用.Add(T); 方法而不使用.Remove(T); ,那么索引将是Count - 1

上述就是C#学习教程:如何在C#中获取列表中新添加项的索引?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1033593.html

(0)
上一篇 2022年1月18日
下一篇 2022年1月18日

精彩推荐