首页 新闻 赞助 找找看

用Dictionary只能遍历最后一个?

0
悬赏园豆:5 [已解决问题] 解决于 2012-08-07 16:14
        readonly Dictionary<Label, string> _myDic = new Dictionary<Label, string>();
        private new void Events()
        {
            var url = "www.8kmm.com";
            _myDic.Add(lblBaiduSL, string.Format("http://www.baidu.com/s?wd=site%3A{0}", url));//百度收录
            _myDic.Add(lblSougouSL, string.Format("http://www.sogou.com/web?query=site%3A{0}", url));//搜狗
            _myDic.Add(lblBingSL, string.Format("http://cn.bing.com/search?q=site%3A{0}", url));//Bing收录
            _myDic.Add(lblSoSoSL, string.Format("http://www.soso.com/q?w=site%3A{0}", url));//soso
            _myDic.Add(lblYouDaoSL, string.Format("http://www.youdao.com/search?q=site%3A{0}", url));//有道
            _myDic.Add(lblYaHooSL, string.Format("http://tool.cnzz.com/yahoo/search.php?q=http://{0}", url));//雅虎 
            _myDic.Add(lblGoogleSL, string.Format("http://www.google.com.hk/search?hl=zh-CN&q=site%3A{0}", url));//谷歌
             
            foreach (var item in _myDic)
            {
                item.Key.Tag = item.Value;
                ((Label)item.Key).Click += delegate { ButtonCLick(item.Key.Tag); };
            }
        }
        void ButtonCLick(object a)
        {
            Process.Start(a.ToString());
        }

Dictionary里保存了Label对象、和它的Tag值, 

我用循环去给页面上的Label增加点击事件, object a 的值全是最后一个?  这个怎么修改?

问天何必的主页 问天何必 | 老鸟四级 | 园豆:3311
提问于:2012-08-05 13:33
< >
分享
最佳答案
1

这是个closure,  这样应该就可以了

foreach (var item in _myDic)
            {
                item.Key.Tag = item.Value;
                var value = item.Value;
                ((Label)item.Key).Click += delegate { ButtonCLick(value); };
            }
收获园豆:5
gunsmoke | 老鸟四级 |园豆:3592 | 2012-08-05 16:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册