c# - 使用相同类型的对象时生成 Cast 异常

标签 c# asp.net .net dictionary

我以前使用静态变量来保存我想在回发之间保存的变量数据。我遇到了问题,发现当 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 是数据绑定(bind)的:

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.Dictionary2[System.String,linkButtonObject] cannot be cast to [B]System.Collections.Generic.Dictionary2[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'.

我不明白当我在所有地方都使用同一个类时怎么会出现转换问题。我做错了什么,我该如何解决?

最佳答案

感谢大家的意见,这帮助我找到了问题。

我在 .aspx.cs 页面中有我的简单类:

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

这就是程序集加载两次并导致问题的原因。

关于c# - 使用相同类型的对象时生成 Cast 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19716712/

相关文章:

c# - 通过更改 Razor 中的 url 获取 View

c# - 错误 "CS0104: ' DataType' 是 'System.ComponentModel.DataAnnotations.DataType' 和 'CarlosAg.ExcelXmlWriter.DataType"之间的不明确引用

c# - 如何在外部浏览器中打开 webBrowser 控件中的链接?

.net - 如何验证 JsonSchema 类型属性中的多个 $ref

c# - Windows 7 - 禁用关闭程序/调试程序对话框,但崩溃转储并通知用户

c# - 将值与 Azure 连接字符串的 PowerShell 脚本分开

c# - 如何检查列表中的任何单词是否包含部分字符串?

mysql - quartz 和 MySQL 6.9.9

c# - .NET 自定义事件组织帮助

c# - 在 .NET 中填充整数列表