A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李拴同 中级黑马   /  2012-12-26 11:18  /  1498 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

看着杨老师视频关于索引器 不理解 请求大家帮助啊  把这个程序解释一下吧,有点理解不了
namespace 索引
{
  class program
  {
    static void main(string[] args)
     int[] values={1,2,4,6};//这里声明数组是干什么的啊?
     int i=values[1];
     Person p1= new Person();
      p1[1]="小明"//这个语法是怎么回事啊?
     Console.WriteLine(p1[1]+p1[2]);
     console.ReadKey();
   }
  class Person
  {
    private string FirstName="大猫"
    private  string SecondName="二毛"
    public string this[int index]
     {set
         {
            if(index==1)
               {FirstName=value;}
            else if(index==2)
                {SecondName=value;}
             else
               {
                 throw new Exception("错误的序列号");
                 }
         }
        get
        {
          if(index==1){return FristName;}
          else if (index==2){return SecondName;}
        else
          {
            throw new Exception("错误的序号");
           }
         }}

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

6 个回复

倒序浏览
  int[] values={1,2,4,6};//这里声明数组是干什么的啊?
     int i=values[1];
上面2句话 是举个例子 告诉你 在 数组中  可以用 下标 (索引器)来访问数组元素


p1[1]="小明"//这个语法是怎么回事啊?
这句话是一个 赋值语句 要结合下面的语句来看 看 set方法
set
         {
            if(index==1)
               {FirstName=value;}
            else if(index==2)
                {SecondName=value;}
             else
               {
                 throw new Exception("错误的序列号");
                 }
告诉你说  当 下标为1 的时候  给FirstName 赋值
下标为2的时候  给 LastName 赋值

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
第一个数组是个一般的数组,应该是对比用的,来说明索引器允许您按照与数组相同的方式对类、结构或接口进行索引。
p1是索引器的实例,由Person类内声明:public string this[],

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
王继光 发表于 2012-12-26 11:23
int[] values={1,2,4,6};//这里声明数组是干什么的啊?
     int i=values[1];
上面2句话 是举个例子 告 ...

不是LAstName吧 应该是SecondName吧  假如是3的话 是不是就是访问的数组中第三个元素呢?我理解的对吗
回复 使用道具 举报
这个 set方法中 没写 当[]中是 3的时候 怎么样, 要按照 代码来的 你想让他[]中等于3的时候 给哪个属性赋值就让它对哪个属性赋值 不一定非是 第3个。

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
这个索引不是从0开始的,而是看你索引器中怎么定义的,public string this[int index],index值,就有2种,(if==1,和if==2)。

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
黄林 中级黑马 2012-12-28 13:33:29
7#
给你看看集合中的索引,对比一下吧:

public abstract class Animal
   {
      protected string name;

      public string Name
      {
         get
         {
            return name;
         }
         set
         {
            name = value;
         }
      }

      public Animal()
      {
         name = "The animal with no name";
      }

      public Animal(string newName)
      {
         name = newName;
      }
   }
public class Animals : CollectionBase
   {
      public Animal this[int animalIndex]
      {
         get
         {
            return (Animal)List[animalIndex];
         }
         set
         {
            List[animalIndex] = value;
         }
      }
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马