1、在 8 中对随机数类 Random 提供了 GetItems() 方法,可以根据指定的数量在提供的一个集合中随机抽取数据项生成一个新的集合:
ReadOnlySpan<string> colors = new[]{"Red","Green","Blue","Black"}; string[] t1 = Random.Shared.GetItems(colors, 10); Console.WriteLine(JsonSerializer.Serialize(t1)); //输出:["Black","Green","Blue","Blue","Green","Blue","Green","Black","Green","Blue"] //每次都会不一样 Console.ReadKey();
2、通过 Random 提供的 Shuffle() 方法,可以将一个集合中的数据项的顺序打乱:
string[] colors = new[]{"Red","Green","Blue","Black"}; Random.Shared.Shuffle(colors); Console.WriteLine(JsonSerializer.Serialize(colors)); Console.ReadKey();
标签:Blue,Shuffle,GetItems,Random,colors,Green,Black,Console From: https://www.cnblogs.com/handsomeziff/p/17993857