最近在看書時看到一段VB.Net的代碼.
Select Case itemType
Case ListItemType.Header
cell.Text = HeaderText
Case ListItemType.Item, ListItemType.AlternatingItem
AddHandler cell.DataBinding, AddressOf ItemDataBinding
Case ListItemType.EditItem
AddHandler cell.DataBinding, AddressOf EditItemDataBinding
Dim DDL As New DropDownList
cell.Controls.Add(DDL)
End Select
想把這段代碼翻譯成C#,碰到了兩個問題.一,當使用開關語句時,符合兩種情況執行相同的代碼,VB.net中用個逗號分隔就OK了( Case ListItemType.Item, ListItemType.AlternatingItem),而C#中似乎沒有這種寫法.今天偶然看到一段代碼,發現連寫連個case中間不加break就OK了.二,關於AddHandler cell.DataBinding, AddressOf ItemDataBinding的含義,在尋找資料後發現是VB中關聯事件和方法的寫法,類似C#中的事件訂閱.翻譯後的C#代碼如下:
switch (itemType)
{
case ListItemType.Header:
{
cell.Text=HeaderText;
break;
}
case (ListItemType.Item):
case(ListItemType.AlternatingItem):
{
cell.DataBinding += new System.EventHandler(ItemDataBinding);
break;
}
// case(ListItemType.AlternatingItem):
// {
// cell.DataBinding += new System.EventHandler(ItemDataBinding);
// break;
// }
case(ListItemType.EditItem):
{
cell.DataBinding += new System.EventHandler(EditItemDataBinding);
DropDownList ddl=new DropDownList();
cell.Controls.Add(ddl);
break;
}
}
不知道大家有沒有更好的寫法,