版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
思路:用一个List集合进行存取需要随机的范围,每次随机出来的数字为List的index,每次随机完将List中的index对应的值删除,最终取的就是删除的数字。
下面以随机生成0~9的四个不同的随机数为例
具体代码如下:
Random rd = new Random();
List<int> nList = new List<int>();
for( int i = 0; i < 10; i++ ) {
nList.Add( i );
}
for( int i = 0; i < 4; i++ ) {
int nNum = rd.Next( nList.Count );
Console.WriteLine( nList[ nNum ] );//先把需要删除的值进行取出来。
nList.Remove( nList[ nNum ] );//也可以写成nList.RemoveAt( nNum )
}
这样的话效率相对较高,因为随机生成的过程只执行四次。