我怎样才能缩短这个通用列表?我的问题很简单:如何进一步缩短这段代码?列表buttonList=newList();buttonList.Add(button1);buttonList.Add(button2);buttonList.Add(button3);buttonList.Add(button4);buttonList.Add(button5);buttonList.Add(button6);buttonList.Add(button7);buttonList.Add(button8);buttonList.Add(button9);如果您的按钮存储在某些控件(例如Form或Panel)的Controls集合中,那么您可以使用://here`this`issupposedtobea`Form`ListbuttonList=this.Controls.OfType().OrderBy(b=>b.Name).ToList();在这种情况下,您可以使用您的方法,返回一个存储在容器控件中的可枚举按钮:publicIEnumerableGetButtons(){returnthis.Controls.OfType().OrderBy(b=>b.Name);//返回this.panel1.Controls.OfType().OrderBy(b=>b.Name);//实际上任何容器控件中都有你的按钮}你可以使用这个:foreach(ButtonbinGetButtons()){//...}尝试集合初始化ListbuttonList=newList(){button1,button2,button3,button4,button5,button6,button7,button8,button9}您可以使用集合初始值设定项:varbuttonList=newList{button1,button2,button3,//...};您可以使用集合初始值设定项:That'sitforC#LearningTutorial:Howtoshortenthisgenericlist?分享的所有内容,如果对你有用,需要进一步了解C#学习教程,希望大家多加关注—ListbuttonList=newList{button1,button2,button3,button4,button5,button6,button7,button8,button9,}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
