• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#索引器

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

一、概要

索引器使你可从语法上方便地创建类、结构或接口,以便客户端应用程序可以像访问数组一样访问它们。编译器将生成一个 Item 属性(或者如果存在 IndexerNameAttribute,也可以生成一个命名属性)和适当的访问器方法。在主要目标是封装内部集合或数组的类型中,常常要实现索引器。例如,假设有一个类 TempRecord,它表示 24 小时的周期内在 10 个不同时间点所记录的温度(单位为华氏度)。此类包含一个 float[] 类型的数组 temps,用于存储温度值。通过在此类中实现索引器,客户端可采用 float temp = tempRecord[4] 的形式(而非 float temp = tempRecord.temps[4])访问 TempRecord 实例中的温度。索引器表示法不但简化了客户端应用程序的语法;还使类及其目标更容易直观地为其它开发者所理解。

语法声明:

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

二、应用场景

这里分享一下设计封装的角度使用索引器,场景是封装一个redis的helper类。在此之前我们先看一个简单的官方示例。

using System;

class SampleCollection<T>
{
   // Declare an array to store the data elements.
   private T[] arr = new T[100];

   // Define the indexer to allow client code to use [] notation.
   public T this[int i]
   {
      get { return arr[i]; }
      set { arr[i] = value; }
   }
}

class Program
{
   static void Main()
   {
      var stringCollection = new SampleCollection<string>();
      stringCollection[0] = "Hello, World";
      Console.WriteLine(stringCollection[0]);
   }
}
// The example displays the following output:
//       Hello, World.

RedisHelper类的封装(伪代码),这样用的好处是不用在需要设置redis的db号而大费周章。

public class RedisHelper
{
    private static readonly object _lockObj = new object();
    private static RedisHelper _instance;
    private int dbNum;

    private RedisHelper() { }

    public static RedisHelper Instance 
    {
        get 
        {
            if (_instance == null)
            {
                lock (_lockObj)
                {
                    if (_instance == null)
                    {
                        _instance = new RedisHelper();
                    }
                }
            }
            return _instance;
        }
    }

    public RedisHelper this[int dbid] 
    {
        get
        {
            dbNum = dbid;
            return this;
        }
    }

    public void StringSet(string content) 
    {
        Console.WriteLine($"StringSet to redis db { dbNum }, input{ content }.");
    }
}

调用:

RedisHelper.Instance[123].StringSet("测试数据");

运行效果:

 

 

Reference:

https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/this?f1url=%3FappId%3DDev16IDEF1%26l%3DZH-CN%26k%3Dk(thisCSharpKeyword);k(TargetFrameworkMoniker-.NETFramework,Version%253Dv4.0);k(DevLang-csharp)%26rd%3Dtrue?WT.mcid=WDIT-MVP-5004326

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/indexers/using-indexers?WT.mc_id=WDIT-MVP-5004326

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/indexers/?WT.mc_id=WDIT-MVP-5004326


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
在C++中实现C#的delegate机制发布时间:2022-07-10
下一篇:
字符串的处理[C#]发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap