这篇文章主要简单介绍C#索引器,索引器使你可从语法上方便地创建类、结构或接口,以便客户端应用程序可以像访问数组一样访问它们。编译器将生成一个 Item 属性和适当的访问器方法,在主要目标是封装内部集合或数组的类型中,常常要实现索引
一、概要
索引器使你可从语法上方便地创建类、结构或接口,以便客户端应用程序可以像访问数组一样访问它们。编译器将生成一个 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("测试数据");
运行效果:
到此这篇关于浅谈C#索引器的文章就介绍到这了,更多相关C#索引器内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
本文标题为:浅谈C#索引器


基础教程推荐
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C# 解析XML和反序列化的示例 2023-04-14
- C#中 Json 序列化去掉null值的方法 2022-11-18
- 实例详解C#实现http不同方法的请求 2022-12-26
- Unity shader实现高斯模糊效果 2023-01-16
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#中的Linq to JSON操作详解 2023-06-08