淺談C#索引器
一、概要
索引器使你可從語法上方便地創(chuàng)建類、結(jié)構(gòu)或接口,以便客戶端應(yīng)用程序可以像訪問數(shù)組一樣訪問它們。編譯器將生成一個 Item 屬性(或者如果存在 IndexerNameAttribute,也可以生成一個命名屬性)和適當(dāng)?shù)脑L問器方法。在主要目標(biāo)是封裝內(nèi)部集合或數(shù)組的類型中,常常要實(shí)現(xiàn)索引器。例如,假設(shè)有一個類 TempRecord,它表示 24 小時的周期內(nèi)在 10 個不同時間點(diǎn)所記錄的溫度(單位為華氏度)。此類包含一個 float[] 類型的數(shù)組 temps,用于存儲溫度值。通過在此類中實(shí)現(xiàn)索引器,客戶端可采用 float temp = tempRecord[4] 的形式(而非 float temp = tempRecord.temps[4] )訪問 TempRecord 實(shí)例中的溫度。索引器表示法不但簡化了客戶端應(yīng)用程序的語法;還使類及其目標(biāo)更容易直觀地為其它開發(fā)者所理解。
語法聲明:
public int this[int param]
{
get { return array[param]; }
set { array[param] = value; }
}
二、應(yīng)用場景
這里分享一下設(shè)計封裝的角度使用索引器,場景是封裝一個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類的封裝(偽代碼),這樣用的好處是不用在需要設(shè)置redis的db號而大費(fèi)周章。
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 }.");
}
}
調(diào)用:
RedisHelper.Instance[123].StringSet("測試數(shù)據(jù)");
運(yùn)行效果:

到此這篇關(guān)于淺談C#索引器的文章就介紹到這了,更多相關(guān)C#索引器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)對二維數(shù)組排序的方法
這篇文章主要介紹了C#實(shí)現(xiàn)對二維數(shù)組排序的方法,實(shí)例分析了C#數(shù)組遍歷與排序的相關(guān)技巧,需要的朋友可以參考下2015-06-06
c#使用EPPlus將圖片流嵌入到Excel實(shí)現(xiàn)示例
這篇文章主要為大家介紹了c#使用EPPlus將圖片流嵌入到Excel實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
C#自動類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解
今天小編就為大家分享一篇關(guān)于C#自動類型轉(zhuǎn)換與強(qiáng)制類型轉(zhuǎn)換的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
C#數(shù)值轉(zhuǎn)換-顯式數(shù)值轉(zhuǎn)換表(參考)
就是在將一種類型轉(zhuǎn)換成另外一種類型時,需要額外的代碼來完成這種轉(zhuǎn)換。2013-04-04
C#根據(jù)IP地址查詢所屬地區(qū)實(shí)例詳解
這篇文章主要介紹了C#根據(jù)IP地址查詢所屬地區(qū)實(shí)例詳解,調(diào)用的接口是免費(fèi)的接口,有需要的同學(xué)可以研究下2021-03-03

