【发布时间】:2017-12-20 16:45:07
【问题描述】:
我有一个设置为 GUID 列表的会话变量。我需要将该 GUID 列表转换为字符串。我对会话变量知之甚少,并且对 C# 的经验有限,因此我尝试了以下可能愚蠢的解决方案:
Session["OtherProgramIDs"] 的类型为 object{System.Collections.Generic.List<System.Guid?>}
不起作用,给我“InvalidCastException”,
无法转换类型的对象 'System.Collections.Generic.List
1[System.Nullable1[System.Guid]]' 键入'System.Collections.Generic.List`1[System.String]'":
var otherProgramList = (List<string>)Session["OtherProgramIDs"];
不起作用,这给了我一条消息,说“对象不包含 Select 的定义并且没有扩展方法 Select 接受对象类型的第一个参数”:
var otherProgramList = Session["OtherProgramIDs"].Select(x => (string)x).ToList();
这给了我与上面相同的信息:
var otherProgramList = Session["OtherProgramIDs"].Select(x => x.ToString()).ToList();
我是否需要使用 .ToString() 循环遍历它,然后添加到 otherProgramList 或其他东西?
编辑
我已经添加了上面的错误消息。也尝试过 cmets 的这个建议,并收到上面关于 System.Collections.Generic.List yada yada yada 的相同突出显示的错误。
var otherProgramList = ((IEnumerable<Guid>)Session["OtherProgramIDs"]).Select(x => x.ToString()).ToList();
仅供参考 - 这个 GUID 可以为空是可以的,还有其他限制因素在起作用。
【问题讨论】:
-
((IEnumerable<Guid>)Session["OtherProgramIDs"]).Select(x => x.ToString()).ToList() -
定义“不起作用”。你得到了什么例外?
-
调试的时候
Session["OtherProgramIDs]返回的值是什么类型的? (我不是指object- 索引器的返回类型,我是指返回对象的真实类型)。 “不起作用”是什么意思?如果您告诉我们错误消息,我们可以帮助您快 200%。如果您使用x.ToString()而不是(string)x,我敢打赌您的第二种方法有效。因为GUID不能强制转换为string,但有ToString()方法。 -
Guid 不是字符串,因此您不能将其转换为字符串。使用
ToString()从 GUID 生成字符串。检查文档以获取适用于Guid.ToString()的格式说明符 -
你到底在
Session["OtherProgramIDs"]中存储了什么?