C#索引器
来源:互联网 发布:迪杰斯特拉算法 简单 编辑:程序博客网 时间:2024/06/06 03:16
假设我们要定义一个类 Employee,它带有3个string型字段,那么可以使用字段的名称来访问它们。
如:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Learning{ class Employee { public string LastName; public string FirstName; public string CityOfBirth; } class Program { static void Main(string[] args) { Employee emp1 = new Employee(); emp1.LastName = "Doe"; emp1.FirstName = "Jane"; emp1.CityOfBirth = "Dallas"; Console.WriteLine("{0}", emp1.LastName); Console.WriteLine("{0}", emp1.FirstName); Console.WriteLine("{0}", emp1.CityOfBirth); } }}
然而有的时候,使用索引访问它们会更加的方便。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Learning{ class Employee { public string LastName; public string FirstName; public string CityOfBirth; public string this[int index] { set { switch (index) { case 0: LastName = value; break; case 1: FirstName = value; break; case 2: CityOfBirth = value; break; default : throw new ArgumentOutOfRangeException("index"); } } get { switch (index) { case 0: return LastName; case 1: return FirstName; case 2: return CityOfBirth; default : throw new ArgumentOutOfRangeException("index"); } } } } class Program { static void Main(string[] args) { Employee emp1 = new Employee(); emp1[0] = "Doe"; emp1[1] = "Jane"; emp1[2]= "Dallas"; Console.WriteLine("{0}", emp1[0]); Console.WriteLine("{0}", emp1[1]); Console.WriteLine("{0}", emp1[2]); } }}
阅读全文
0 0
- C#索引器
- C#索引器
- C#索引器
- C#中的索引器
- C#索引器
- C# 索引器
- C#索引器
- C#索引器
- C# 索引器
- C#索引器
- C#索引器
- C#索引器
- C#索引器
- c#属性 索引器
- C#的索引器
- C#索引器
- C#索引器
- C#索引器
- spring初次搭建碰到问题 Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 7; 不允许有匹配 "[xX
- 微信支付银行卡交易的限额是多少?
- Java实现爬虫给App提供数据(Jsoup 网络爬虫)
- 170620 How to install tensorflow with GPU on linux
- Learning to Rank(LTR)
- C#索引器
- 工程师们,留点时间和妹子约个会吧
- 【原创】Eclipse vs. IDEA快捷键对比大全
- MFC-资源文件
- 采购计算方案的确定
- ubuntu安装IntelliJ Idea
- IOS核心动画高级五:变换
- Linux(centOS)下查看服务器环境和系统配置
- out