索引器

https://docs.microsoft.com/zh-cn/dotnet/csharp/indexers 学习笔记

索引器语法:

通过变量名和方括号访问索引器,使用this关键字作为“属性名”声明索引器,并在方括号里声明索引器参数。

using System;
using System.Collections.Generic;

namespace ConsoleApp4
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testIndex = new TestIndexer();
            testIndex[""] = 23;
            testIndex[""] = 9;
            Console.WriteLine(testIndex[""]);
            Console.ReadLine();
        }
    }

    public class TestIndexer
    {
        private Dictionary<string, int> storage = new Dictionary<string, int>();

        // 可以使用public,protected,internal,private,private protected,protected internal修饰符
        public int this[string key]
        {
            get { 
                if (storage.ContainsKey(key)) 
                {
                    return storage[key]; 
                }
                else 
                {
                    return 0;
                }; 
            }
            set
            {
                storage[key] = value;
            }
        }
    }
}

索引器应用举例:

通过索引器可提供与类型的抽象化匹配的 API,而无需公开如何存储或计算此抽象化的值的内部细节。(类似于反射)

分页。

对字典的加工。

using System;
using System.Collections.Generic;

namespace ConsoleApp4
{
    class Program
    {
        public static void Main(string[] args)
        {
         
            Console.ReadLine();
        }
    }

    public class ArgsProcessor
    {
        private readonly ArgsActions actions;

        public ArgsProcessor(ArgsActions actions)
        {
            this.actions = actions;
        }

        public void Process(string[] args)
        {
            foreach (var arg in args)
            {
                actions[arg]?.Invoke();
            }
        }

    }
    public class ArgsActions
    {
        // 使用readonly,避免其他地方实例化该对象
        readonly private Dictionary<string, Action> argsActions = new Dictionary<string, Action>();

        // 只读索引器
        public Action this[string s]
        {
            get
            {               
                Action action;
                Action defaultAction = () => { };
                return argsActions.TryGetValue(s,out action) ? action : defaultAction;
            }
        }

        public void SetOption(string s, Action a)
        {
            argsActions[s] = a;
        }
    }
}
View Code

多维映射。

   public class Mandelbrot
    {       
        // 参数不规定同一类型
        public double this[double x, double y]
        {
            get
            {
                return x * y;
            }
        }
    }

只要类中有类似于属性的元素就应创建索引器,这个属性索引器不是一个值,而是值的集合,其中每一个项由一组参数标识,这组参数允许多个

 

posted @ 2020-03-15 12:48  舒碧  阅读(223)  评论(0编辑  收藏  举报