|
使用C# Indexer
Indexer是C#中新增加的,可能有些朋友会有些困惑,最近做的一些事情 经常使用Index,顺手写一个简单的例子给大家看看,如果有什么问题可以问! 这个例子包含三个类:DataRow、DataItem、DataItemCollection。 其中DataItemCollection中使用了Indexer。 using System; using System.Collections; public static void Main(string [] args) { DataRow myDataRow = new DataRow(); DataItem myDataItem = new DataItem("Text","Value"); DataRow.DataItems.Add(myDataItem); Console.WriteLine(myDataRow.DataItems[0].Text); } public class DataRow { public DataItemCollection DataItems; public DataRow() { DataItems = new DataItemCollection(); } } public class DataItem { private string _text; private string _value; public DataItem(string text, string value) { _text=text; _value=value; } public string Text { get { return(_text); } set { _text=value; } } public string Value { get { return(_value); } set { _value=value; } } } public class DataItemCollection { private ArrayList _array = new ArrayList(); public virtual int Count { get { return(_array.Count); } } public DataItem this[int index] //此处使用了Indexer { get { if(index>=0 && index<_array.Count) { return((DataItem)_array[index]); } else { throw new Exception("index overflow"); } } set { if(index>=0 && index<_array.Count) { _array[index]=value; } else { throw new Exception("index overflow"); } } } public void Add(DataItem item) { _array.Add(item); }
public void Remove(DataItem item) { _array.Remove(item); } public void RemovAt(int i) { _array.RemoveAt(i); } }
上一篇文章: C#使用技巧--调用DLL
下一篇文章: C++编程人员容易犯的10个C#错误
|
专题栏目
最新推荐
相关文章
Java高级学习:Java代码编 JRun3.0配合IIS的安装全 Windows下JSP开发环境的 使用lomboz调试JSP 在Linux上架设支持JSP+P 使用Eclipse开发Jsp JSP与XML的结合 Freebsd+Resin成功建立支 JSP开发前菜鸟设置篇 入门教程:JSP标准模板库
|