我可以使用随机类从数组列表中随机检索一个对象,我知道我不能将这个随机检索的对象存储在变量中
using System;
using System.Threading;
using System.Collections;
namespace ThreadSample
{
class FunWithVehicles
{
public void VehicleThread1()
{
Console.WriteLine("Type Of Vehicle Is Car\nRegisteration Number Is: TN0098 1234\nLicense Number Is APK32456\nVehicle Number Is 1");
}
public void VehicleThread2()
{
Console.WriteLine("Type Of Vehicle Is Van\nRegisteration Number Is: TN0012 2385\nLicense Number Is UKL37899\nVehicle Number Is 2");
}
public void VehicleThread3()
{
Console.WriteLine("Type Of Vehicle Is Truck\nRegisteration Number Is: TN1798 8907\nLicense Number Is MNT59863\nVehicle Number Is 3");
}
public void VehicleThread4()
{
Console.WriteLine("Type Of Vehicle Is Tanker\nRegisteration Number Is: TN3987 5357\nLicense Number Is RTJ23498\nVehicle Number Is 4");
}
public void VehicleThread5()
{
Console.WriteLine("Type Of Vehicle Is Bus\nRegisteration Number Is: TN9768 3212\nLicense Number Is RTJ98734\nVehicle Number Is 5");
}
}
class TollGate
{
\\ retrieving the randomly stored object happens here and it will check a parameter
\\ The Parameter Function is to check whether the sent object was already sent and to see whether the previous number is remaining since all the threads have to be sent sequentially
}
class Simulate
{
public static void Main()
{
Simulate s = new Simulate();
Simulate n = new Simulate();
FunWithVehicles f = new FunWithVehicles();
ThreadStart Ref1 = new ThreadStart(f.VehicleThread1);
ThreadStart Ref2 = new ThreadStart(f.VehicleThread2);
ThreadStart Ref3 = new ThreadStart(f.VehicleThread3);
ThreadStart Ref4 = new ThreadStart(f.VehicleThread4);
ThreadStart Ref5 = new ThreadStart(f.VehicleThread5);
Thread Th1 = new Thread(Ref1);
Thread Th2 = new Thread(Ref2);
Thread Th3 = new Thread(Ref3);
Thread Th4 = new Thread(Ref4);
Thread Th5 = new Thread(Ref5);
ArrayList items = new ArrayList();
items.Add(Th1);
items.Add(Th2);
items.Add(Th3);
items.Add(Th4);
items.Add(Th5);
Random rnd = new Random();
int r = rnd.Next(items.Count);
// storing will happen here and it will be sent to the TollGate class to check the parameter
// If there are no previous numbers and if is not sent, it will be processed and displayed in the TollGate class and decremented from the array list right here in the simulate class, so the next time only 4 objects will be remaining and once all the threads are processed the application stops
}
}
我想随机选择一个对象并将其存储,以便将其发送到另一个类。我不知道究竟要放在参数函数中以使其工作以及如何使减量部分工作。 任何帮助将不胜感激。对于显示我得到了Thread.Start();但如何在现有代码中融合它以使其工作。如何对线程或函数进行编号,以便它知道顺序处理线程。
答案 0 :(得分:2)
为什么不呢。
使用Random
类Next(int minvalue, int maxvalue)
方法给出小于数组列表长度的值。
然后使用该随机值作为索引从数组列表中获取值。
这样
ArrayList ar = new ArrayList();
//Fill Array List
Random r = new Random();
int rand = r.Next(0, ar.Count);
var value = ar[rand];
答案 1 :(得分:0)
您可以使用已有的随机数,并执行此操作。
object picked = items[rnd.Next(0,items.Count)];