我有以下功能:
//Function to get random number
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
Run Code Online (Sandbox Code Playgroud)
我怎么称呼它:
byte[] mac = new byte[6];
for (int x = 0; x < 6; ++x)
mac[x] = (byte)(Misc.RandomNumber((int)0xFFFF, (int)0xFFFFFF) % 256);
Run Code Online (Sandbox Code Playgroud)
如果我在运行时使用调试器执行该循环,则会得到不同的值(这就是我想要的).但是,如果我在该代码下面放置一个断点两行,则"mac"数组的所有成员都具有相同的值.
为什么会这样?
我有一个递归函数,在函数中选择了一个数组中的随机元素,但无论我做什么,我都会得到相同的种子.
static Random rand = new Random();
public String spintaxParser(String s)
{
if (s.Contains('{'))
{
int closingBracePosition = s.IndexOf('}');
int openingBracePosition = closingBracePosition;
while (!s[openingBracePosition].Equals('{'))
openingBracePosition--;
String spintaxBlock = s.Substring(openingBracePosition, closingBracePosition - openingBracePosition + 1);
String[] items = spintaxBlock.Substring(1, spintaxBlock.Length - 2).Split('|');
s = s.Replace(spintaxBlock, items[rand.Next(items.Length)]);
return spintaxParser(s);
}
else
{
return s;
}
}
Run Code Online (Sandbox Code Playgroud)
在递归函数中处理Random的最佳方法是什么?
我一直在编写一些C#代码用于训练练习,其中我必须创建一个随机矩形数组.
问题是我的GetRandomRectangle函数生成的矩形始终是相同的.我System.Random用来生成矩形的坐标.
我意识到这是因为Random对象是使用默认构造函数创建的,因此具有相同的种子.我已修改它以便为每个矩形获取不同的种子,它工作正常.
问题是 - 它如何决定'默认种子'?我注意到它似乎也没有随着时间的推移而改变,用种子2创建的矩形将始终被赋予相同的尺寸.
这可能是我可以谷歌的东西,但很高兴听到你们的意见和信息.
谢谢 :)