2013-10-31 35 views
5

我以前使用靜態變量來存放我希望在回發之間保存的變量數據。我遇到了問題,並發現當appdomain結束時,這些變量中的數據會丟失。所以,我做了一些研究,並決定去與ViewStates:使用相同類型的對象時生成的演員異常

static Dictionary<string, linkButtonObject> linkButtonDictonary; 


protected void Page_Load(object sender, EventArgs e) 
{ 
    if (ViewState["linkButtonDictonary"] != null) 
    { 
     linkButtonDictonary = (Dictionary<string, linkButtonObject>)ViewState["linkButtonDictonary"]; 
    } 
    else 
    { 
     linkButtonDictonary = new Dictionary<string, linkButtonObject>(); 
    } 
} 

這裏是非常簡單的類使用:

[Serializable] 
public class linkButtonObject 
{ 
    public string storyNumber { get; set; } 
    public string TaskName { get; set; } 
} 

我加入到linkBut​​tonDictionary作爲一個GridView是數據綁定:

protected void hoursReportGridView_OnRowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     LinkButton btn = (LinkButton)e.Row.FindControl("taskLinkButton"); 
     linkButtonObject currentRow = new linkButtonObject(); 
     currentRow.storyNumber = e.Row.Cells[3].Text; 
     currentRow.TaskName = e.Row.Cells[5].Text; 
     linkButtonDictonary.Add(btn.UniqueID, currentRow); 
    } 
} 

看來我以前的問題已經解決,但是新的問題已經出現。有時,當我回發我收到此錯誤:

[A]System.Collections.Generic.Dictionary 2[System.String,linkButtonObject] cannot be cast to [B]System.Collections.Generic.Dictionary 2[System.String,linkButtonObject]. Type A originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Type B originates from 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'LoadNeither' at location 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'.

我不明白,怎麼可以有一個鑄造的問題時,我使用的是同一類無處不在。我做錯了什麼,如何解決?

+1

不知何故,你已經設法在不同的加載上下文中加載相同的程序集(mscorlib)。你是使用'Assembly.LoadFrom()'或類似的方式加載mscorlib或其他可以加載它的組件? – Pete

+1

您可以嘗試使用Fusion Log Viewer來追蹤問題:http://msdn.microsoft.com/en-us/library/e74a18c4%28VS.71%29.aspx – Pete

+0

我不會以編程方式加載任何程序集,並且甚至不知道mscorlib是什麼。 –

回答

3

感謝大家的意見,它幫助我追蹤了這個問題。

我有我的簡單的類在.aspx.cs頁:

[Serializable] 
public class linkButtonObject 
{ 
    public string storyNumber { get; set; } 
    public string TaskName { get; set; } 
} 

這就是爲什麼組件被加載兩次,導致了問題。

+1

有趣!感謝分享,至少這個問題有一個直接相關的解決方案! – Abhinav

+0

嗨。那麼你在哪裏放置類定義呢? :) – Carlos

2

這個長相酷似以下問題:

InvalidCastException when serializing and deserializing

至於解決,它可能是在你的控制手柄組件負載等

一個簡單的方法是XML序列化/ JSON將數據作爲字符串序列化並將該字符串保存在ViewState中。爲了獲得它,你只需要改變過程。這將確保重複加載問題。