【发布时间】:2014-08-09 23:15:48
【问题描述】:
我在下面的代码中遇到了一个尴尬的问题。
在第一种方法(加载时)中,我尝试将存储在视图状态中的字典转移到变量“dict”中。
我收到错误“无法将类型“对象”隐式转换为字典”。
我已经厌倦了没有成功的类型转换。我在这里做错了什么?
提前致谢!
PS(我开始使用视图状态的原因是页面重新加载时下面列表框中的选择消失了)
public partial class _Default : System.Web.UI.Page
{
Dictionary<string, int> dict = new Dictionary<string, int>();
protected void Page_Load(object sender, EventArgs e)
{
//throws the implicit conversion error
if (ViewState["dict"] != null) {
dict = ViewState["dict"];
//dict = (Dictionary<string, int>)ViewState["dict"];
}
Response.Write("Reload");
foreach (ListItem li in ListBox1.Items) {
if (dict.ContainsKey(li.Value)) {
if (dict[li.Value] == 3) {
li.Attributes.Add("style", "background-color: green;");
Label3Items.Text += "<br>" + li.Text;
}
else if (dict[li.Value] == 2) {
li.Attributes.Add("style", "background-color: blue;");
Label2Items.Text += "<br>" + li.Text;
}
else if (dict[li.Value] == 1) {
li.Attributes.Add("style", "background-color: yellow;");
Label1Items.Text += "<br>" + li.Text;
}
else {
li.Attributes.Add("style", "background-color: red;");
LabelVetoItems.Text += "<br>" + li.Text;
}
}
}
}
protected void updateName(object sender, EventArgs e)
{
Label1.Text = "Welcome "+TextBox1.Text+"!";
}
protected void Button1_Click(object sender, EventArgs e) {
Updater(3);
}
protected void Button2_Click(object sender, EventArgs e) {
Updater(2);
}
protected void Button3_Click(object sender, EventArgs e) {
Updater(1);
}
protected void ButtonVeto_Click(object sender, EventArgs e) {
Updater(0);
}
protected void Updater(int indexer) {
//loops through listitems, color-marks selected items and stores to dictionary
foreach (ListItem li in ListBox1.Items) {
if (li.Selected == true) {
//li.Enabled = false;
if (indexer == 3) {
li.Attributes.Add("style", "background-color: green;");
Label3Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 3);
}
else if (indexer == 2) {
li.Attributes.Add("style", "background-color: blue;");
Label2Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 2);
}
else if (indexer == 1) {
li.Attributes.Add("style", "background-color: yellow;");
Label1Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 1);
}
else{
li.Attributes.Add("style", "background-color: red;");
LabelVetoItems.Text += "<br>" + li.Text;
dict.Add(li.Value, 0);
}
}
}
//stores the dictionary with updates key-pair objects from user selection
ViewState["dict"] = dict;
}
protected void submit_Click(object sender, EventArgs e) {
//unfinished
}
}
【问题讨论】:
-
你究竟是如何尝试投射的?
-
在评论中添加了我使用的语法。我还是一条弯弯曲曲的红线。
-
那么当你尝试这样投射时会出现什么错误?
-
错误是“无法将类型“对象”隐式转换为 System.Collections.Generic.Dictionary”,我仔细检查了语法是否正确。难道是字典没有序列化?
-
好吧,显然这是VS中的错误。我之前更新了一个答案,以免混淆其他人。对不起!
标签: c# asp.net dictionary casting viewstate