2011-11-22 74 views
0

我的程序中有几个独立的int变量。有没有一种方法,我可以将其中一个随机馈入新的int变量或int数组?提前致谢。c#:从几个随机选择一个变量

编辑:

这里是一个伪代码来演示:

int A1 = 1; 
int A2 = 3; 
int RESULT = 0; 

Random rand = new Random(); 

Result = rand.Next(0, A1 || A2)]; //Result holds the value/variable name of A1 or A2 
+0

你能添加你想要达到什么样的一些伪代码?我不认为这个问题是明确的,或者它的目的。请扩大。 – agarcian

+0

@agarcian,我按照你的要求添加了 – jonatr

回答

2

你可以把所有你想从一个新的数组来选择,然后从中选择一个随机值的整数。例如:

int value1 = 3; 
int anotherValue = 5; 
int value2 = 1; 

int[] selectableInts = new int[3] { value1, anotherValue, value2 }; 

Random rand = new Random(); 

int randomValue = selectableInts[rand.Next(0, selectableInts.Length)]; 
0

如何:

// create an array of your variables 
int[] A = new int[] {1,3}; 

// Instantiate Random object. 
Random rand = new Random(); 

// Get a value between 0 and the lenght of your array. 
// This is equivalent to select one of the elements of the array. 
int index = rand.Next(0,A.Length); 

// Get the value from the array that was selected at random. 
int Result = A[index];