.NET Server全力进攻企业市场
By Stuart J. Johnston
Microsoft已经开始着手部署Web Service平台上的企业应用程序。 [更多信息]

再谈JAXB
By Daniel F. Savarese
在一个升级版本和规范草案出台之际,让我们再来回顾一下JAXB。[更多信息]

运用VB.NET的面向对象的特征
By Francesco Balena
通过运用继承性和其它面向对象的功能,编写漂亮的、易于维护的代码。 [更多信息]

For-Each问题
Question:
我从DictionaryBase中继承了一个类,但For-each就出问题了,错误信息是"Specified cast
is not valid", 请问是怎么回事?

Public Class Customer 
Private m_CustName As String 
Public ReadOnly Property CustName() 
Get 
Return m_CustName 
End Get 
End Property 
Public Sub New(ByVal NewName As String) 
m_CustName = NewName 
End Sub 
End Class 

Public Class Customers 
Inherits DictionaryBase 
Public Sub Add(ByVal NewEntry As Customer, ByVal NewKey As String) 
Dictionary.Add(NewKey, NewEntry) 
End Sub 
Default Public ReadOnly Property Item(ByVal Key As String) As Customer 
Get 
Return CType(Dictionary.Item(Key), Customer) 
End Get 
End Property 
End Class 

Module Module1 
Sub Main() 
Dim colCust As New Customers() 
Dim cust As Customer 
colCust.Add(New Customer("Joe"), "Joe") 
colCust.Add(New Customer("Ann"), "Ann") 
Try 
'this does work! 
Console.WriteLine(colCust("Joe").CustName) 
'this does not work! 
For Each cust In colCust 
Console.WriteLine(cust.CustName) 
Next 
Catch ex As Exception 
Console.WriteLine(ex.ToString) 
End Try 
Console.ReadLine() 
End Sub 
End Module 

Answer:
上面的代码肯定会导致invalid cast异常。因为对于DictoinaryBase类来说,你每次都会从For Each语句提取DictionaryEntry类。该异常就是说你不能将一个DictionaryEntry转换成Customer类。所以可以试试下面的代码:


Dim de As DictionaryEntry 
For Each de In colCust 
cust = CType(de.Value, Customer) 
Console.WriteLine(cust.CustName) 
Next