日期:2014-05-18  浏览次数:20679 次

求释疑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IndexText
{
  public class Photo
  {
  string title;
  public Photo(string title)
  {
  this.title = title;
  }
  public string Title
  {
  get
  {
  return this.title;
  }
  }
  }
  class Album
  {
  Photo[] photos;
  public Album(int num)
  {
  photos = new Photo[num];
  }
  public Photo this[int index]
  {
  get
  {
  return photos[index];
  }
  set
  {
  photos[index] = value;
  }
  }
  public Photo this[string title]
  {
  get
{
for(int i=0;i<photos.Length;i++)
  {
  if (photos[i].Title == title)
  {
  return photos[i];
  }
  }
  Console.WriteLine("没有找到");
  }
  }
  }
  class Test
  {
  static void Main(string[] args)
  {
  Photo julia = new Photo("julia");
  Photo mark = new Photo("mark");
  Album friends = new Album(20);
  friends[0] = julia;
  friends[1] = mark;
  Photo obj = friends[1];
  Console.WriteLine(obj.Title);
  obj = friends["julia"];
  Console.WriteLine(obj.Title);
  Console.ReadLine();
  }
  }
}
这个get编译出错,能不能帮个忙给解答个,为什么编译时错误提示为:错误 “IndexText.Album.this[string].get”: 并非所有的代码路径都返回值

------解决方案--------------------
已经说的很清楚了:“并非所有的代码路径都返回值”
C# code

get
{
    for(int i=0;i<photos.Length;i++)
    {
        if (photos[i].Title == title)
        {
            return photos[i];
        }
    }
    Console.WriteLine("没有找到");

    // 没有找到的话返回什么呢???
}

------解决方案--------------------
Console.WriteLine("没有找到");
return null;