• c#里面的索引器注意


    1、特此说明,下面代码是从完整部分复制了部分,未必能直接拷贝执行。

    2、索引器里注意  1)如果没有设置数组保存,不能连续访问per2[0],per[1],因为里面的比如 Name是被替换的。 2)我们创建数组保存,需要 创建空间,我们可以

    string[] ArrName=new string[10] ; 也可以在这里分配空间
    也可以写个构造方法,动态分配空间,如下面代码。

    3、索引器里另外灵活运用例子,将索引号不同,给对象不同字段赋值。

    public string this [int index]
                {
                    set
                    {
                        if (index == 0)
                        { Name = "test1"; }
                        else if (index == 1)
                            Name = "testOther";
                        else
                            Name = value;
                    }
                    get
                    {
                        if (index == 0)
                            return Name;
                        else if (index == 1)
                            return Name + 1;
                        else
                            return Name;
                      
                    }调用      //索引器,不能一次性访问per2【0】,per2【1】,除非把 return保存到数组里面
               person per2 = new person();
                per2[0] = "11";
                Console.WriteLine(per2[0]);
                per2[1] = "22";
                Console.WriteLine(per2[1]);
                per2[2] = "33";
                Console.WriteLine(per2[2]);
                Console.WriteLine(per2[0]+" "+per2[1]+" "+per2[2]+" "+per2[3]);
    static void Main(string[] args)
    {
    
    person per2 = new person();
    per2[0] = "11";
    Console.WriteLine(per2[0]);
    per2[1] = "22";
    Console.WriteLine(per2[1]);
    per2[2] = "33";
    Console.WriteLine(per2[2]);
    Console.WriteLine(per2[0]+" "+per2[1]+" "+per2[2]+" "+per2[3]);
    
     
    
    Console.ReadKey();
    }
    
    
    
    public class person
    {
    int age;
    string name;
    // string[] ArrName=new string[10] ; 也可以在这里分配空间
    string[] ArrName;
    private bool sex;
    public person(int i)//构造方法,为ArrName分配空间
    {
    ArrName = new string[i];
    }
    public string this [int index]
    {
    set
    {
    if (index == 0)
    { ArrName[0] = "test1"; }
    else if (index == 1)
    ArrName[1] = "testOther";
    else
    ArrName[index] = value;
    }
    get
    {
    if (index == 0)
    return ArrName[index];
    else if (index == 1)
    return ArrName[index];
    else
    return ArrName[index] +100;
    
    }
    }
      
  • 相关阅读:
    mybatis-plus代码生成模板
    Flask_APScheduler的简单使用
    Linux 配置mysql 远程连接
    ubuntu19.04 安装mysql,没有初始密码,重设初始密码
    ubuntu19.04 配置远程连接ssh
    python3 win 建立虚拟环境(virtualenv)
    python property(不动产)方法
    python,装饰器带参数,原理
    利用python装饰器为字符串添加,HTML标签
    python pymysql 基本使用
  • 原文地址:https://www.cnblogs.com/ilrc/p/7076375.html
Copyright © 2020-2023  润新知