您的位置:首页 > 其它

每秒改变一次背景颜色以及由此引发的一些有趣的小事情(.net方向)

2012-10-19 16:05 330 查看
简单的一个小题目:窗体每秒变一次背景颜色
确实简单,上代码:
方案1:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
Init();
}

private void Init()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler((o, p) =>
{
Thread.Sleep(TimeSpan.FromSeconds(1));
});
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler((o, p) =>
{
this.Background = new SolidColorBrush(Color.FromRgb(GetRandom(), GetRandom(), GetRandom()));
Init();
});
worker.RunWorkerAsync();
}

private byte GetRandom()
{
var num = Convert.ToByte(new Random().Next(0, 255));
Debug.WriteLine(num);
return num;
}


很简单的一个循环,算是一个递归嘛,用异步进行,之所以用异步,是如果你不用异步,窗体会等待数据而造成卡......
自然不是为了说这个,来说说一个有趣的事儿,hi,这里,看这里,

private byte GetRandom()
{
var num = Convert.ToByte(new Random().Next(0, 255));
Debug.WriteLine(num);
return num;
}


我写了一个Debug输出,为什么呢?先看结果



look,有图有真相,同一个函数加载的random函数返回来的数值有很大部分相同,这个问题之前写连连看的时候就出现过,random函数看起来随机,但是,实际上并没有你想要的结果,同义词调用连续使用一个上限和下线得到的种子会有联系,这个好像别人已经说过了。。。不多说了,换上限和下线或者重新new一个random都行,也就是
a=new random();b=new random()这样的就可以解决

这种方法比较简单,而且简单,我的意思是,我们是拉风的程序员,代码太简单会不会影响我们的拉风形象,(⊙o⊙),那就来点拉风的
方案2:

PropertyInfo[] props;
static int i = -1;

public MainWindow()
{
InitializeComponent();
props = typeof(Brushes).GetProperties(BindingFlags.Public | BindingFlags.Static);
DispatcherTimer tm = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Normal, (object sender, EventArgs e) =>
{
i=i > props.Length ? 0 : i + 1;
this.Background = (Brush)props[i].GetValue(null, null);
}, Dispatcher);
}


用DispatcherTimer来搞,每秒一次,反射来取Brushes的public和static集,然后static变量累加,取得颜色,赋值。
这个看起来似乎稍微符合程序员的身份了,但是static int i=-1;这句话不好,不符合命名规范嘛,而且 static累加好像都能想到,能不能稍微再改进改进
这个真可以

private int num;
public int GetNum
{
get { return num; }
set { num = value; }
}

private static readonly DependencyPropertyKey numKey =
DependencyProperty.RegisterReadOnly("Num",typeof(int),typeof(MainWindow),new PropertyMetadata(0));

public int Num
{
get { return (int)GetValue(numKey.DependencyProperty); }
}

public MainWindow()
{
InitializeComponent();
props = typeof(Brushes).GetProperties(BindingFlags.Public | BindingFlags.Static);
DispatcherTimer tm = new DispatcherTimer(TimeSpan.FromSeconds(1), DispatcherPriority.Normal, (object sender, EventArgs e) =>
{
GetNum = GetNum > props.Length ? 0 : GetNum + 1;
this.Background = (Brush)props[GetNum].GetValue(null, null);
//SetValue(numKey, Num > props.Length ? 0 : Num + 1);
//this.Background = (Brush)props[Num].GetValue(null, null);
}, Dispatcher);

}


属性,依赖属性,都可以充当这个角色
至于 反射,依赖属性这个就不多说了
http://files.cnblogs.com/fish124423/XMAL.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: