首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

用Dictionary不得不遍历最后一个? 这个写法错在哪

2012-10-08 
用Dictionary只能遍历最后一个? 这个写法错在哪?C# codereadonly DictionaryLabel, string _myDic new

用Dictionary只能遍历最后一个? 这个写法错在哪?

C# code
        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 的值全是最后一个? 这个怎么修改?

[解决办法]
暂且按照你的代码,应该改为
C# code
            foreach (var item in _myDic)            {                var c= item;                item.Key.Tag = item.Value;                ((Label)item.Key).Click += delegate { ButtonCLick(c.Key.Tag); };            } 

热点排行