欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

淺談C#索引器

 更新時(shí)間:2021年11月03日 15:59:14   作者:老王Plus  
這篇文章主要簡(jiǎn)單介紹C#索引器,索引器使你可從語(yǔ)法上方便地創(chuàng)建類(lèi)、結(jié)構(gòu)或接口,以便客戶(hù)端應(yīng)用程序可以像訪(fǎng)問(wèn)數(shù)組一樣訪(fǎng)問(wèn)它們。編譯器將生成一個(gè) Item 屬性和適當(dāng)?shù)脑L(fǎng)問(wèn)器方法,在主要目標(biāo)是封裝內(nèi)部集合或數(shù)組的類(lèi)型中,常常要實(shí)現(xiàn)索引器,下面我們一起來(lái)看看具體內(nèi)容吧

一、概要

索引器使你可從語(yǔ)法上方便地創(chuàng)建類(lèi)、結(jié)構(gòu)或接口,以便客戶(hù)端應(yīng)用程序可以像訪(fǎng)問(wèn)數(shù)組一樣訪(fǎng)問(wèn)它們。編譯器將生成一個(gè) Item 屬性(或者如果存在 IndexerNameAttribute,也可以生成一個(gè)命名屬性)和適當(dāng)?shù)脑L(fǎng)問(wèn)器方法。在主要目標(biāo)是封裝內(nèi)部集合或數(shù)組的類(lèi)型中,常常要實(shí)現(xiàn)索引器。例如,假設(shè)有一個(gè)類(lèi) TempRecord,它表示 24 小時(shí)的周期內(nèi)在 10 個(gè)不同時(shí)間點(diǎn)所記錄的溫度(單位為華氏度)。此類(lèi)包含一個(gè) float[] 類(lèi)型的數(shù)組 temps,用于存儲(chǔ)溫度值。通過(guò)在此類(lèi)中實(shí)現(xiàn)索引器,客戶(hù)端可采用 float temp = tempRecord[4] 的形式(而非 float temp = tempRecord.temps[4] )訪(fǎng)問(wèn) TempRecord 實(shí)例中的溫度。索引器表示法不但簡(jiǎn)化了客戶(hù)端應(yīng)用程序的語(yǔ)法;還使類(lèi)及其目標(biāo)更容易直觀(guān)地為其它開(kāi)發(fā)者所理解。

語(yǔ)法聲明:

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

二、應(yīng)用場(chǎng)景

這里分享一下設(shè)計(jì)封裝的角度使用索引器,場(chǎng)景是封裝一個(gè)redishelper類(lèi)。在此之前我們先看一個(gè)簡(jiǎn)單的官方示例。

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類(lèi)的封裝(偽代碼),這樣用的好處是不用在需要設(shè)置redisdb號(hào)而大費(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("測(cè)試數(shù)據(jù)");


運(yùn)行效果:

到此這篇關(guān)于淺談C#索引器的文章就介紹到這了,更多相關(guān)C#索引器內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論