Visual Studio 2010——C#中的属性与索引器
来源:互联网 发布:推荐算法的选择 编辑:程序博客网 时间:2024/06/05 15:24
实验环境:Windows XP,Visual Studio 2010 Ultimate
类的索引器与属性功能类似,它可以把类虚拟成一个数组,可以按照访问数组的方式对类的数据进行访问,从而实现对数据的保护和隐藏。和属性一样,索引器的读写也是通过get,set访问器进行的,但是不同的是,它们需要参数。
1 创建项目
文件>>新建>>项目,选中“控制台应用程序”,如下图所示:
2 添加代码如所示意。
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace PropertyIndexApp{ class MyClass { private const int c_count = 100; private static int[] intArray = new int[c_count]; //第一个索引器,可读写,有两个参数 public int this[int index, int offset] { get { if ((index + offset) >= 0 && (index + offset) < c_count) { return intArray[index + offset]; } else return 0; } set { if ((index + offset) >= 0 && (index + offset) < c_count) { intArray[index+offset] = value; } } } private int m_strCount = 3; private string[] strArray = { "111","222","333"}; //第二个索引器,只读,一个参数 public string this[int index] { get { if ((index >= 0) && (index < m_strCount)) { return strArray[index]; ; } else return "NULL"; } } //实例属性,可读写 public int StrCount { get { return m_strCount; } set { if (value > m_strCount) { strArray = new string[value]; for (int i = 0; i < value; i++) { strArray[i] = string.Format("String No.{0}",i); } m_strCount = value; } } } private static string m_strName = "MyClass"; //静态属性,只读 public static string ClassName { get { return m_strName; } } } class Program { static void Main(string[] args) { MyClass m = new MyClass(); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { //读写第一个索引器 m[i * 10, j] = i * 10 + j; Console.Write("No.{0}{1}:{2}",i,j,m[i*10,j]); } Console.WriteLine(); } for (int i = 0; i < m.StrCount; i++) { //读第二个索引器 Console.WriteLine(m[i]); } //实例属性写操作 m.StrCount = 5; //实例属性读操作 for (int i = 0; i < m.StrCount; i++) { //读第二个索引器 Console.WriteLine(m[i]); } //静态属性读操作 Console.WriteLine(MyClass.ClassName); } }}
3 调试
单击菜单栏的“调试”|“启动调试”,结果如下图。
4 工程源码。点击这里下载。
参考资料
《C#实用编程百例》,清华大学出版社,何鹏飞,王征等 编著
《C#程序设计——基础教程与实验指导》——清华大学出版社,孙晓非 牛小平 冯冠 李乃文 编著
《C#程序设计与案例教程》,清华大学出版社,杨树林,胡洁萍 编著
- Visual Studio 2010——C#中的属性与索引器
- Visual Studio 2010——C#中的装箱拆箱操作与Object类型
- Visual Studio 2010——C#中的类
- Visual Studio 2010——C#中的事件
- Visual Studio 2010——C#中的委托
- Visual Studio 2010——C#中的命名空间
- Visual Studio 2010——C#中的字符串
- Visual Studio 2010——C#中的异常处理
- Visual Studio 2010——C#中的Unsafe模式
- Visual Studio 2010——C#中的值类型
- C#索引器与属性
- c#中的字段 属性 索引器
- [C#基础教程]之快速了解c#中的索引器及与属性区别
- C#之属性与索引器
- C#中方法,属性与索引器
- C# 索引器与属性的区别
- Visual Studio 2010——C#的DateTimePicker与MonthCalendar控件的使用
- C#索引器-索引器与数组属性的比较
- 黑马程序员-IO流 File类及Properties类
- 4.1改动
- 使用spinner 做下拉对话框
- 腾讯笔试题--国王招来100个囚犯
- linux kernel make
- Visual Studio 2010——C#中的属性与索引器
- 随想录(关于培训)
- 字符数组和字符指针
- JAVA的文件操作
- 哈夫曼编码
- IOS Socket使用大全 -将持续更新
- 计算机视觉整理备忘
- Compilers(Dragon Book 2nd) - 4.9
- RMI网络编程 重启server端程序,client端无法连接