zoukankan      html  css  js  c++  java
  • C#基础 索引器及其重载代码示例

        class Animal
        {
            private Dictionary<string, int> indexer1 = new Dictionary<string, int>();
            private string[] indexer2 = new string[10];
            //从indexer1取值的索引器
            public int this[string index]
            {
                get
                {
                    if (indexer1.ContainsKey(index))
                        return indexer1[index];
                    else
                        throw new Exception("未找到对应值");
                }
                set
                {
                    if (indexer1.ContainsKey(index))
                        indexer1[index] = value;
                    else
                        indexer1.Add(index, value);
                }
            }
            //从indexer2取值的索引器
            public string this[int index]
            {
                get
                {
                    if (index < 10 && !string.IsNullOrEmpty(indexer2[index]))
                        return indexer2[index];
                    else if (index >= 10)
                        throw new IndexOutOfRangeException();
                    else
                        throw new Exception("未找到对应值");
                }
                set
                {
                    if (index < 10)
                        indexer2[index] = value;
                    else
                        throw new IndexOutOfRangeException();
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                Animal animal = new Animal();
                //第一个索引器
                animal["Fish"] = 20;
                animal["Tiger"] = 100;
                animal["Mouse"] = 5;
                //第二个索引器
                animal[1] = "Dog";
                animal[2] = "Cat";
                animal[3] = "Bird";
            }
        }
  • 相关阅读:
    使文字背景透明
    文件拷贝
    鼠标选取图象的实现
    刷新整个画布
    将区域的颜色取反
    用API处理位图
    用TImageList动态画透明图片
    将bmp文件转换为jpg文件
    解决phpmyadmin-1800秒超时链接失效问题
    Linux下解压命令大全
  • 原文地址:https://www.cnblogs.com/vsSure/p/8024802.html
Copyright © 2011-2022 走看看