【问题标题】:Declaring a indexer in a class example.在类示例中声明索引器。
【发布时间】:2014-04-03 05:38:14
【问题描述】:

当我在 Main() 中运行这个程序时,它不断给我错误消息,说“Tommy”、“Bulldog”和“Male”在当前上下文中不存在。我想不通为什么?在我添加这些字符串之前,该程序运行良好。谁能帮我理解一下?

namespace indexusingthismethod
{
  public class Dog
  {
   private string name;
   private string breed;
   private string gender;

  public Dog()  
  { 
  name = "Fido";
  breed = "Mongrel";
  gender = "Male";
  }

  public Dog(string dogName, string dogBreed, string dogGender)
  { 
  name = dogName;
  breed = dogBreed;
  gender = dogGender;
  }
  public string Name    
  { 
  get { return name; }
  set { name = value; }
  }

  public string Breed  
  { 
    get { return breed; }
    set { breed = value; }
  }
  public string Gender
  {
   get { return gender; }
   set { gender = value; }
  }
  public string this[int index]
  {
   set
   {
      switch (index)
      {
           case 0: name = value;
               break;
           case 1: breed = value;
               break;
           case 2: gender = value;
               break;
           default: throw new ArgumentOutOfRangeException("index");
      }
  }
  get
   {
       switch (index)
       {
           case 0: return name;
           case 1: return breed;
           case 2: return gender;
           default: throw new ArgumentOutOfRangeException("index");
        }
   }
 }
 public void Bark()
 {
  Console.WriteLine("{0} said: Woof!", name);
 }
} 

public class Doggies
{
static void Main()
{

 Dog descriptionofDog = new Dog(); 
 Console.WriteLine("Dog name: {0}\nDog breed: {1}\nDog gender: {2}\n", descriptionofDog [0], descriptionofDog [1],
 descriptionofDog [2]);
 descriptionofDog[0] = Tommy;
 descriptionofDog[1] = Bulldog;
 descriptionofDog[2] = Male;

 Console.WriteLine("Dog name: {0}\nDog breed: {1}\nDog gender: {2}\n",descriptionofDog[0], descriptionofDog[1],
 descriptionofDog[2]);

【问题讨论】:

  • 它们是字符串文字吗?他们不见了"s...
  • 试图找出过去 30 分钟的错误。 3秒内搞定。谢谢。

标签: c# class indexer


【解决方案1】:

Dog 上有 3 个字符串属性。 NameBreedGender

当你建立 descriptionofDog 对象时,你去掉了告诉编译器这些是对象,而不是字符串的引号。

只需在字符串文字周围加上引号:

descriptionofDog[0] = "Tommy";
descriptionofDog[1] = "Bulldog";
descriptionofDog[2] = "Male";

【讨论】:

  • 谢谢。不敢相信我无法弄清楚这个简单的错误。
  • @Rayhose,我们都制作了它们。祝你好运!
【解决方案2】:

添加到@paq...的答案。以下是创建新 Dog 对象而不是使用 indexer 的更简单方法。

 Dog descriptionofDog = new Dog();

descriptionofDog = new Dog("Tommy", "Bulldog", "Male");

descriptionofDog = 
 new Dog() { Name = "Tommy", Breed = "Bulldog", Gender = "Male" };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多