C# .NET 索引器的基本使用
索引器和属性差不多,属性是一对一,而索引器是一对多而已。
(一) int 索引
class Program
{
static void Main(string[] args)
{
MyClass mc = new MyClass();
mc[0] = "胡文杰";
mc[1] = "杨佳";
Console.WriteLine(mc[0]);
Console.WriteLine(mc[1]);
Console.Read();
}
}
class MyClass
{
private string[] name = new string[2];
// 关键:用 this 代替,类型也可以用 string
public string this[int index] {
get {
if (index >= 0 && index < name.Length) {
return name[index];
}
else {
return name[0];
}
}
set {
if (index >=0 && index < name.Length) {
name[index] = value;
}
}
}
}
输出:
胡文杰
杨佳
string 索引
using System;
namespace RefTest
{
class Employee
{
public string name;
public string Age;
public string Gender;
public Employee(string n, string a, string g)
{
name = n;
Age = a;
Gender = g;
}
public string this[string str] {
set {
switch (str) {
case "姓名":
name = value;
break;
case "年龄":
Age = value;
break;
case "性别":
Gender = value;
break;
//default:
//throw new Exception().Message;
}
}
get {
switch (str) {
case "姓名": return name;
case "年龄": return Age;
case "性别": return Gender;
default:
throw new ArgumentOutOfRangeException("index");
}
}
}
class Program
{
static void Main()
{
Employee employee = new Employee("周杰伦", "12", "男");
Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);
Console.WriteLine("\n改名:");
employee["姓名"] = "猪八戒";
Console.WriteLine(employee["姓名"] + " " + employee["年龄"] + " " + employee["性别"]);
Console.ReadKey();
}
}
}
}
输出:
周杰伦 12 男
改名:
猪八戒 12 男
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了