[A]List`1[MyObject] cannot be cast to [B]List`1[MyObject]

Description

 I have created a small class in a single ASP.NET 4.5 web forms page that is instantiated and then stored in a List, then saved/loaded from ViewState:

<Serializable>
Private Class _PageLevelToolTip
    Public ClientId As String
    Public TipText As String
End Class

Private Property _pageLevelToolTipCollection As List(Of _PageLevelToolTip)
    Get
        Return ViewState("_toolTipCollection")
    End Get
    Set(value As List(Of _PageLevelToolTip))
        ViewState("_toolTipCollection") = value
    End Set
End Property

This class only appears on one page in the whole application.  
Users are reporting an intermittent error on subsequent page loads:

    [A]System.Collections.Generic.List1[selfassessment+_PageLevelToolTip] cannot be cast to [B]System.Collections.Generic.List1[selfassessment+_PageLevelToolTip].

    Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:WindowsMicrosoft.NetassemblyGAC_64mscorlibv4.0_4.0.0.0__b77a5c561934e089mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:WindowsMicrosoft.NetassemblyGAC_64mscorlibv4.0_4.0.0.0__b77a5c561934e089mscorlib.dll'.

After searching for days I found a tip that seems to solve the issue, by casting to the type explicitly:

Private Property _pageLevelToolTipCollection As List(Of _PageLevelToolTip)
    Get
        Return CType(ViewState("_toolTipCollection"), List(Of _PageLevelToolTip)) ' Revision here '
    End Get
    ' Setter removed for brevity '
End Property

Is this a bug?  
We cannot test this accurately because of the wildly intermittent nature. This is a page-level private object and list that only exist in a single page.

Although the error does not trigger in the above manner, I can recreate it by doing the following process:

    1. Load page (ensuring class is saved within viewstate)
    2. Edit page in VS and save
    3. Load page (to load class from Viewstate)

This would imply that the object changes in some way part-way through postbacks, although it's structure does not, or the compiled page changes and won't recognise the original. 

I hope this helps in the diagnosis.  Another person is reporting the same fault from a different approach, but the answer given does not help here: https://connect.microsoft.com/VisualStudio/feedback/details/779108/xaml-designer-in-vs2012-throws-invalidcastexception

 來源:http://cncc.bingj.com/cache.aspx?q=%5bA%5dSystem.Collections.Generic.List+cannot+be+cast+to+%5bB%5dSystem.Collections.Generic.List&d=4976373898546130&mkt=zh-CN&setlang=zh-CN&w=p1PWhpihlQ3W_kwkM-AEL10hUnZb69sm

原文地址:https://www.cnblogs.com/CoreXin/p/4857175.html