• C# 类中索引器的使用


    请看代码,下面是类的定义,中间包含了一个索引器定义

    类的定义 
        public class Person
        {
            //定义两个字段信息
            private string name;
            private string password;

            //定义一个 Name 属性来操作 name 字段
            public string Name
            {
                set { name = value; }
                get { return name; }
            }

            //定义一个 Password 属性来操作 password 字段
            public string Password
            {
                set { password = value; }
                get { return password; }
            }

            //定义索引器,name 字段的索引值为 0 ,password 字段的索引值为 1
            public string this[int index]
            {
                get
                {
                    if (index == 0return name;
                    else if (index == 1return password;
                    else return null;
                }
                set
                {
                    if (index == 0) name = value;
                    else if (index == 1) password = value;
                }
            }
        }

     

    下面是使用索引器的方法:

    protected void Page_Load(object sender, EventArgs e)
        {
            //声明并实例化这个类
            Person p = new Person();

            //使用索引器的方式来给类的两个属性赋值
            p[0] = "jarod";
            p[1] = "123456,./";

            //使用类属性取得两个字段信息
            Label1.Text = p.Name + " / " + p.Password;
        }
    索引器使用

        
     

     

          非常简单,在上面的类中我们把类的 name 字段映射的索引值为 0,而 password 字段映射的索引值为 1。有了这个映射就可以使用以下方式为类的 name 和 password 赋值了。

            p[0= "jarod";    //设置 name 字段值
            p[1= "123456,./";  //设置 password 字段值

     

    赋值后,就可以使用属性方法访问到刚刚给两个字段赋的值了。


  • 相关阅读:
    实现可重启线程
    让别人能登陆你的mysql
    zmq消息订阅
    git备忘
    【LeetCode】数组排列问题(permutations)(附加next_permutation解析)
    【LeetCode】 数相加组合 Combination Sum
    【LeetCode】【找元素】Find First and Last Position of Element in Sorted Array
    【LeetCode】【数组归并】Merge k Sorted Lists
    【LeetCode】【动态规划】Generate Parentheses(括号匹配问题)
    【Leetcode】Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/yasin/p/2384052.html
Copyright © 2020-2023  润新知