问题描述
我特林创建随机抽取的颜色。有一个错误。你能帮我这个code。
私人随机随机的; 私人无效MainForm_Load(对象发件人,EventArgs的发送)
{
随机=新的随机();
} 私人颜色GetRandomColor()
{
返回Color.FromArgb(random.Next(0,255),random.Next(0,255),random.Next(0,255));
//错误是在这里
} 公共SolidBrush brushGet()
{
SolidBrush oBrush =新SolidBrush(GetRandomColor());
返回oBrush;
}
我不明白上述code,比以前它被称为不被初始化的Random对象之外的任何问题。也有完全没有必要在窗体的Load事件对其进行初始化;这是可以做到权当它宣称:
私有静态只读随机随机=新的随机();
我个人倒是不声明它的局部范围内,因为据我所知,你的每一次,如果你去了解这种方式结束了相同的值。我还亲自看不到的东西过于复杂的需求;产生随机数和每次使用 Color.FromAgb()
方法,你应该罚款。
I am tring to create random drawing colors. There is an error. Could you help me about this code.
private Random random;
private void MainForm_Load(object sender, EventArgs e)
{
random = new Random();
}
private Color GetRandomColor()
{
return Color.FromArgb(random.Next(0, 255), random.Next(0,255),random.Next(0,255));
// The error is here
}
public SolidBrush brushGet()
{
SolidBrush oBrush = new SolidBrush(GetRandomColor());
return oBrush;
}
I don't see any problems with the above code, other than the Random object not being initialized before it is called to. There is also absolutely no need to initialize it in the Load event of the form; it can be done right when it's declared:
private static readonly Random Random = new Random();
Personally I'd not declare it on local scope, as far as I know you end up with the same value every time if you go about it that way. I also personally don't see the need of overcomplicating things; generating random numbers everytime and using the Color.FromAgb()
method you should be fine.
这篇关于创建随机颜色(的System.Drawing.Color)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!