淺談C#索引器
一、概要
索引器使你可從語法上方便地創(chuàng)建類、結(jié)構(gòu)或接口,以便客戶端應(yīng)用程序可以像訪問數(shù)組一樣訪問它們。編譯器將生成一個 Item 屬性(或者如果存在 IndexerNameAttribute,也可以生成一個命名屬性)和適當(dāng)?shù)脑L問器方法。在主要目標(biāo)是封裝內(nèi)部集合或數(shù)組的類型中,常常要實現(xiàn)索引器。例如,假設(shè)有一個類 TempRecord,它表示 24 小時的周期內(nèi)在 10 個不同時間點所記錄的溫度(單位為華氏度)。此類包含一個 float[] 類型的數(shù)組 temps,用于存儲溫度值。通過在此類中實現(xiàn)索引器,客戶端可采用 float temp = tempRecord[4] 的形式(而非 float temp = tempRecord.temps[4] )訪問 TempRecord 實例中的溫度。索引器表示法不但簡化了客戶端應(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# 動態(tài)調(diào)用WebService的示例
這篇文章主要介紹了C# 動態(tài)調(diào)用WebService的示例,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2020-11-11
c#中的浮點型轉(zhuǎn)整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼
c#中的浮點型轉(zhuǎn)整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼,學(xué)習(xí)c#的朋友可以參考下2012-03-03
C#中winform窗體實現(xiàn)注冊/登錄功能實例(DBHelper類)
在編寫項目時,編寫了一部分關(guān)于登錄頁面的一些代碼,下面這篇文章主要給大家介紹了關(guān)于C#中winform窗體實現(xiàn)注冊/登錄功能(DBHelper類)的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
基于NPOI用C#開發(fā)的Excel以及表格設(shè)置
這篇文章主要為大家詳細(xì)介紹了基于NPOI用C#開發(fā)的Excel以及表格設(shè)置,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02

