C#索引器的应用:自已写一个表格
2013-08-29 18:33
344 查看
C#中索引器,在一个类中有很多的同一类型成员的时候,比较适用索引器。
环境:我们假设有一个动物园,里边有很多动物。
用法:
1.先定义一个类,这是成员的类型。在这里就是要定义一个Animal类;
2.再定义一个包含索引器的类,在这里是Zoo动物园类。
3.那么我们在主程序里就可以这么用:
好了,接下来,我们来自定义一个我们自己的表格:
1.先定义Cell单元格类
2.定义Row行 类(注意在这里我们必须就得用List<Cell>了。因为它包含很多Cell成员了,下边的Table也是,包含很多row)
3.再定义Table 表格类
4.最后我们在主程序里可以用了:
输出结果:
环境:我们假设有一个动物园,里边有很多动物。
用法:
1.先定义一个类,这是成员的类型。在这里就是要定义一个Animal类;
public class Animal { public string Name { get; set; } }
2.再定义一个包含索引器的类,在这里是Zoo动物园类。
public class Zoo { private List<Animal> animals = new List<Animal>(); public Animal this[int index] { get{return animals[index];} set{animals.Add(value);} } }
3.那么我们在主程序里就可以这么用:
class Program { static void Main(string[] args) { Animal a = new Animal(); a.Name = "老虎"; Animal b = new Animal(); b.Name = "大象"; Zoo z=new Zoo(); z[0] = a; z[1] = b; Console.WriteLine(z[0].Name); Animal c; c = z[1]; Console.WriteLine(c.Name); } }
好了,接下来,我们来自定义一个我们自己的表格:
1.先定义Cell单元格类
class Cell { public string Text { get; set; } }
2.定义Row行 类(注意在这里我们必须就得用List<Cell>了。因为它包含很多Cell成员了,下边的Table也是,包含很多row)
class Row { private List<Cell> cells = new List<Cell>(); public Cell this[int index] { get { return cells[index]; } set { cells.Add(value); } } }
3.再定义Table 表格类
class Table { private List<Row> rows = new List<Row>(); public Row this[int index] { get { return rows[index]; } set { rows.Add(value); } } }
4.最后我们在主程序里可以用了:
class Program { static void Main(string[] args) { Cell c0= new Cell(); c0.Text = "姓名"; Cell c1 = new Cell(); c1.Text = "性别"; Cell c2=new Cell(); c2.Text="张三"; Cell c3=new Cell(); c3.Text="男"; Row row = new Row(); row[0] = c0; row[1] = c1; Row row2 = new Row(); row2[0] = c2; row2[1] = c3; Table table = new Table(); table[0] = row; table[1] = row2; //取得表格第0行,第1列的单元格内容 //Console.WriteLine(table[0][1].Text); //取得表格第1行,第0列的单元格内容 //Console.WriteLine(table[1][0].Text); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { Console.Write(table[i][j].Text+" "); } Console.WriteLine(); }
输出结果:
相关文章推荐
- C#索引器的应用:自已写一个表格
- C#的类和方法的一个小应用
- 使用 UITableView 创建表格应用演练(1)——一个简单的表格应用
- C#中如何应用索引器 ( How to use Indexers )
- 分享一个C#自定义事件的实际应用
- C#的类和方法的一个小应用续
- 用C#创建PDF表格:iTextSharp的应用
- 使用C#开发一个简单的P2P应用
- 在C#中向Word 中现有的表格中加行一行,并给每个单元格一个值,要怎么写呀?
- c#将一个word中的内容放到另一个word的表格中
- 一个猜数字的小游戏—C# 控件的动态加载和应用 多线程
- C# 表格跨行和跨列应用实例
- 使用 UITableView 创建表格应用演练(1)——一个简单的表格应用
- C#索引器作用与应用
- Oracle 远程访问配置 在 Windows Forms 和 WPF 应用中使用 FontAwesome 图标 C#反序列化XML异常:在 XML文档(0, 0)中有一个错误“缺少根元素” C#[Win32&WinCE&WM]应用程序只能运行一个实例:MutexHelper Decimal类型截取保留N位小数向上取, Decimal类型截取保留N位小数并且不进行四舍五入操作
- 使用C#开发一个简单的P2P应用
- 工厂模式的又一个应用:商场收费系统(C#源代码)
- .NET委托(在多线程编程中的应用):一个C#睡前故事
- C#综合应用,写一个英语单词类浏览练习软件
- c# sharp 中委托做参数的一个应用