C# OrderedDictionary为只读,无法修改
问: 当我尝试以下代码时:C# OrderedDictionary为只读,无法修改,c#,asp.net,session,collections,ordereddictionary,C#,Asp.net,Session,Collections,Ordereddictionary,问: 当我尝试以下代码时: ((IOrderedDictionary)Session["keys"])[2] = objToUpdate.Note_title; ((IOrderedDictionary)Session["keys"])[3] = objToUpdate.Iscourse; 它抛出一个异常: OrderedDictionary是只读的,并且 无法修改 我的问题: 为什么只是只读 如何在会话中设置密钥,解决我的问题 编辑: 我通过以下方式填写IOrderedDictio
((IOrderedDictionary)Session["keys"])[2] = objToUpdate.Note_title;
((IOrderedDictionary)Session["keys"])[3] = objToUpdate.Iscourse;
它抛出一个异常:
OrderedDictionary是只读的,并且
无法修改
我的问题:
- 为什么只是只读
- 如何在会话中设置密钥,解决我的问题
IOrderedDictionary
:
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
Session["Keys"] = keys;
暴力解决方案是在保存到会话之前将值复制到新字典:
IOrderedDictionary orderedDictionary = new OrderedDictionary();
foreach (KeyValuePair<TKey, TValue> kvp in gv_courses.DataKeys[index].Values)
{
orderedDictionary.Add(kvp.key, kvp.value);
}
Session["Keys"] = keys;
IOrderedDictionary orderedDictionary=new orderedDictionary();
foreach(gv_课程中的KeyValuePair kvp.DataKeys[index].Values)
{
orderedDictionary.Add(kvp.key,kvp.value);
}
会话[“键”]=键;
但是,我强烈建议找到另一种方法来获取密钥,而不使用GridView的DataKeys属性。- 为什么只是只读
- 如何在会话中设置密钥,解决我的问题
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
var keysTemp = new OrderedDictionary();
foreach (DictionaryEntry de in keys)
{
keysTemp.Add(de.Key, de.Value);
}
keys OrderedDictionary与gv_courses.DataKeys[index]值相同,但它没有只读。现在您可以将其保存到会话中:
Session["KeysCourse"] = keysTemp; //keysTemp is equal to keys but is editable
现在代码将运行,因为会话中的OrderedDictionary不再是只读的:
((IOrderedDictionary)Session["KeysCourse"])[2] = objToUpdate.Note_title;
((IOrderedDictionary)Session["KeysCourse"])[3] = objToUpdate.Iscourse;
我达到了我想做的,谢谢所有的回复
IOrderedDictionary keys = gv_courses.DataKeys[index].Values;
string[] keysTemp = new string[4];
keysTemp[0] = keys[0].ToString();
keysTemp[1] = keys[1].ToString();
keysTemp[2] = keys[2].ToString();
keysTemp[3] = keys[3].ToString();
Session["KeysCourse"] = keysTemp;
然后
这在事件
gv\u courses\u row命令中发生。
是否将GridView与ObjectDatasource一起使用?gv\u courses是什么类类型?它从何处获取数据(datasource)?gv\u courses
是GridView
。数据源是一个datatable
。不,我不想这样做,我只想修改会话中的数据,而不是键本身。因为我通过这个iorderedictionary keys=gv_courses.DataKeys[index].value代码>在会话结束后,您应该能够在会话中修改数据。您的意思是您想修改会话[“密钥”]但不想修改密钥?我的错,您需要进行深度复制,但不包含只读部分,序列化它会保存只读状态。欢迎您,我找到了另一种方法来制作密钥的非只读副本,请再次检查我的答案
((string[])Session["KeysCourse"])[2] = objToUpdate.Note_title;
((string[])Session["KeysCourse"])[3] = objToUpdate.Iscourse.ToString();