• C#索引器的使用


    索引器这个东东,我也是最近才接触,一般所说的索引器,是指定义在某个类里面的一个类似属性的东西。索引器是.net中新的类成员。类似与类的属性。有些人干脆称呼它为带参数的属性。

    索引器可以快速定位到类中某一个数组成员的单元。下面看看代码:

    Indexer 
    class indexerClass
    {
    private int[] arr=new int[100];
    private string[] names=new string[100];
    public int this[int index]
    {
    get
    {
    if (index < 0 || index >= 100)
    {
    return -1;
    }
    else
    {
    return arr[index];
    }
    }
    set//索引器的get,set被编译器编译成get_item,sge_item方法。
    {
    if (index >=0 && index < 100)
    {
    arr[index]
    =value;
    }
    }
    }
    public int this[string key]//索引器的参数也可是字符串等,不一定只能是int
    {
    get
    {
    return GetNumber(key);
    }
    }
    public int GetNumber(string Gender)
    {
    if (Gender == "boy")
    {
    return 1;
    }
    else if (Gender == "girl")
    {
    return 0;
    }
    else
    {
    return -1;
    }
    }
    }

    索引器参数大多是int类型,但也可以是其他类型,如string。

    static void Main(string[] args)
    {
    indexerClass indexerTest
    = new indexerClass();
    for (int i = 0; i < 10; i++)
    {
    indexerTest[i]
    = i + 2; //对类的对象,可以直接像操作数组一样操作对象里面的数组。
    }
    for (int i = 0; i < 10; i++)
    {
    Console.WriteLine(indexerTest[i]);
    }
    Console.ReadKey();
    }
  • 相关阅读:
    ES6变量的解构赋值
    ES6新增内容
    Rvalue references
    range-based for statement
    Space in Template Expression, nullptr, and auto
    Type Alias、noexcept、override、final
    Variadic Template
    =default =delete
    为什么不要特化函数模版?
    boost::noncopyable 的作用
  • 原文地址:https://www.cnblogs.com/zhuawang/p/2155744.html
Copyright © 2020-2023  润新知