------------------------
★
Foreach :
优点:
1、不用考虑数组起始索引是几
int[] nArray = new int[100];
// Use "foreach" to loop array
foreach( int i in nArray )
2、对于多维数组操作用foreach非常简便
int[,] nVisited = new int[8,8];
// Use "for" to loop two-dimension array
for( int i = 0; i < nVisited.GetLength(0); i++ )
for( int j = 0; j < nVisited.GetLength( 1 ); j++ )
Debug.WriteLine( nVisited[i,j].ToString() );
// Use "foreach" to loop two-dimension array
foreach( int i in nVisited )
Debug.WriteLine( i.ToString() );
3、foreach类型转换
// Init an arraylist object
int[] nArray = new int[100];
ArrayList arrInt = new ArrayList();
arrInt.AddRange( nArray );
// Use "foreach" to loop an arraylist
foreach( int i in arrInt )
Debug.WriteLine( i.ToString() );
// Use "for" to loop an arraylist
for( int i = 0; i < arrInt.Count; i++ )
{
int n = ( int ) arrInt[i];
Debug.WriteLine( n.ToString() );
}
两个限制
在foreach不能修改枚举成员,其次不要对集合进行删除操作。
// Use "foreach" to loop an arraylist
foreach( int i in arrInt )
{
i++;//Can't be compiled
Debug.WriteLine( i.ToString() );
}
// Use "foreach" to loop an arraylist
foreach( int i in arrInt )
{
arrInt.Remove( i );//It will generate error in run-time
Debug.WriteLine( i.ToString() );
}
附--对于记录集的多条数据删除
可以用for来实现,由于在一些记录集中进行删除的时候,在删除操作之后相应的索引也发生了变化,这时候的删除要反过来进行删除
// Use "for" to loop an arraylist
for( int i = arrInt.Count - 1; i >=0; i-- )
{
int n = ( int ) arrInt[i];
if( n == 5 )
arrInt.RemoveAt( i ); // Remove data here
Debug.WriteLine( n.ToString() );
}
http://blog.csdn.net/huang7914/archive/2008/04/16/2296176.aspx
------------------------
★
------------------------
★
------------------------
★
------------------------
★
------------------------
★
------------------------
★
------------------------
★
---------------------
测试语法高亮的 C# 代码的 html fragment 生成:
用csdn blog API 发布.
下面是:
public class HtmlWriter
{
static Dictionary _colors;
static int _colorNum;
static StringBuilder _colorString;
在asp.net项目中的一个把数据 导出Excel表格的小事件如下:
protected void ibnOut_Click(object sender, ImageClickEventArgs e)//导出Excel按钮的点击事件
{
GridView2.DataSource = dt ......