问题描述
我定义俩个class,一个WorkStation,另外一个是WorkStations。后者是前者的集合对象我在一个WPF程序中调用时,却出现类型转换错误。错误如下:Cannotimplicitlyconverttype'System.Collections.ObjectModel.ReadOnlyCollection<WpfApplication1.WorkStation>'to'WpfApplication1.WorkStation'E:WorkDirLevel4DevWpfApplication1WpfApplication1FileUploadNew.xaml.cs9535WpfApplication1相关的代码:publicclassWorkStation//WorkStation类{privateStringstationName;privateStringstationAddress;privateStringstationPort;privateStringstationListPath;privateStringstationFilePath;publicWorkStation(){}publicStringContent{get{returnstationName;}//To-do-improve}publicStringStationName{get{returnstationName;}set{stationName=value;}}}//WorkStationList类publicclassWorkStationList{privateList<WorkStation>workStations;privateintlength;publicWorkStationList(){workStations=newList<WorkStation>();length=0;ReadWorkStationFile("");}publicReadOnlyCollection<WorkStation>AllWorkStations{get{returnnewReadOnlyCollection<WorkStation>(workStations);}}}//程序中调用代码,出错语句是element=lstStation.AllWorkStations;WorkStationListlstStation=newWorkStationList();WorkStationelement=newWorkStation();String[]arrTV={"WorkStation_1","WorkStation_2","WorkStation_3","WorkStation_4","WorkStation_5"};//Demofor(inti=0;i<lstStation.Length;i++){element=lstStation.AllWorkStations;//wrong-need-improvelstNavigator.Items.Add(element.Content);//lstNavigator.Items.Add(arrTV[i]);//To-do-improve}}catch(Exceptione){MessageBox.Show(e.Message);}
解决方案
解决方案二:
lstStation.AllWorkStations类型是ReadOnlyCollection<WorkStation>element类型是WorkStation肯定会出错改成element=lstStation.AllWorkStations[i]
解决方案三:
确实像你说的,问题解决。多谢!
解决方案四:
一个集合怎么能转成一个对象!!基础不扎实