淺談C#索引器
一、概要
索引器使你可從語法上方便地創(chuàng)建類、結構或接口,以便客戶端應用程序可以像訪問數組一樣訪問它們。編譯器將生成一個 Item 屬性(或者如果存在 IndexerNameAttribute,也可以生成一個命名屬性)和適當的訪問器方法。在主要目標是封裝內部集合或數組的類型中,常常要實現(xiàn)索引器。例如,假設有一個類 TempRecord,它表示 24 小時的周期內在 10 個不同時間點所記錄的溫度(單位為華氏度)。此類包含一個 float[] 類型的數組 temps,用于存儲溫度值。通過在此類中實現(xiàn)索引器,客戶端可采用 float temp = tempRecord[4] 的形式(而非 float temp = tempRecord.temps[4] )訪問 TempRecord 實例中的溫度。索引器表示法不但簡化了客戶端應用程序的語法;還使類及其目標更容易直觀地為其它開發(fā)者所理解。
語法聲明:
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("測試數據");
運行效果:

到此這篇關于淺談C#索引器的文章就介紹到這了,更多相關C#索引器內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
c#中的浮點型轉整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼
c#中的浮點型轉整形的舍取 四舍五入和銀行家舍入實現(xiàn)代碼,學習c#的朋友可以參考下2012-03-03
C#中winform窗體實現(xiàn)注冊/登錄功能實例(DBHelper類)
在編寫項目時,編寫了一部分關于登錄頁面的一些代碼,下面這篇文章主要給大家介紹了關于C#中winform窗體實現(xiàn)注冊/登錄功能(DBHelper類)的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2023-06-06

