问题描述
我是c#新手写了个程序一直报错请大家帮我看看usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Collections;namespace多个参数的索引器{//姓名,课程ID,成绩classCourseScore//课程的分数类{privatestringname;privateintcourseID;privateintscore;publicCourseScore(stringname,intcourseID,intscore){this.name=name;this.courseID=courseID;this.score=score;}publicstringName{get{returnname;}set{name=value;}}publicintCourseID{get{returncourseID;}set{courseID=value;}}publicintScore{get{returnscore;}set{score=value;}}}classCourseScoreIndexer//索引器,用于存取和查询CourseScore{privateArrayListarrCourseScore;publicCourseScoreIndexer(){arrCourseScore=newArrayList();}publicintthis[stringname,intcourseID]{get{foreach(CourseScorecsinarrCourseScore){if(cs.Name==name&&cs.CourseID==courseID){returncs.Score;}return-1;}}set{arrCourseScore.Add(newCourseScore(name,courseID,value));}}}classProgram{staticvoidMain(string[]args){CourseScoreIndexercsi=newCourseScoreIndexer();csi["张三",1]=90;csi["张三",2]=80;csi["张三",3]=85;csi["李四",1]=80;Console.WriteLine(csi["张三",2]);}}}错误信息错误1“多个参数的索引器.CourseScoreIndexer.this[string,int].get”:并非所有的代码路径都返回值D:Backup我的文档VisualStudio2005Projects第二章多个参数的索引器多个参数的索引器Program.cs4513多个参数的索引器
解决方案
解决方案二:
get{foreach(CourseScorecsinarrCourseScore){if(cs.Name==name&&cs.CourseID==courseID){returncs.Score;}return-1;}}
foreach当arrCourseScore的“长度”如果为零的时候,括号内的语句将不会执行,对不对?也就是说returncs.Score;或return-1;语句可能不会执行,这种情况下getter就没有返回值了。因而编译器抱怨“并非所有的代码路径都返回值”。
解决方案三:
namespace多个参数的索引器{//姓名,课程ID,成绩classCourseScore//课程的分数类{privatestringname;privateintcourseID;privateintscore;publicCourseScore(stringname,intcourseID,intscore){this.name=name;this.courseID=courseID;this.score=score;}publicstringName{get{returnname;}set{name=value;}}publicintCourseID{get{returncourseID;}set{courseID=value;}}publicintScore{get{returnscore;}set{score=value;}}}classCourseScoreIndexer//索引器,用于存取和查询CourseScore{privateArrayListarrCourseScore;publicCourseScoreIndexer(){arrCourseScore=newArrayList();}publicintthis[stringname,intcourseID]{get{foreach(CourseScorecsinarrCourseScore){if(cs.Name==name&&cs.CourseID==courseID){returncs.Score;}elsecontinue;}return-1;}set{arrCourseScore.Add(newCourseScore(name,courseID,value));}}}classProgram{staticvoidMain(string[]args){CourseScoreIndexercsi=newCourseScoreIndexer();csi["张三",1]=90;csi["张三",2]=80;csi["张三",3]=85;csi["李四",1]=80;Console.WriteLine(csi["张三",2]);}}}