作者wind681201 (阿风~~)
看板C_Sharp
标题[问题] 静态变数会不见吗?
时间Thu Sep 10 11:05:08 2020
请问各位大大,以下程式码,_users常会因null而错误,
但已经用private static 来宣告了,不是应该不会让_users为null吗?
public static class Users
{
private static Dictionary<string, User> _users = new Dictionary<string,
User>();
public static List<User> AllUser { get { return _users.Select(x=>
x.Value).ToList(); } }
public static void Add(this IIdentity _id, User _user)
{
if (_users is Dictionary<string, User>)
{
_users[_user.ID] = _user; //在这边常会因为 _users是null而错误。
}
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 180.183.247.253 (泰国)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1599707111.A.E15.html
2F:→ awwseed: 不过你的问题应该是 _users[_user.ID] 不存在才炸? 09/10 11:41
3F:→ awwseed: 检查是否存在的话用 .ContainsKey() 可能比较好 09/10 11:43
5F:→ awwseed: 不确定你其他地方是否有对 _users 做操作 09/10 11:58
6F:→ petercoin: 同楼上 key不存在时要用Add 不然就exception了 09/10 12:29
7F:推 Litfal: dict透过的索引键set不会跳错啦 09/10 13:24
8F:→ awwseed: 原来 Dict 透过索引不会炸错XD 09/10 13:37
9F:→ awwseed: 那就比较可能是 Users 里面有其他地方对 _users 有操作? 09/10 13:38
10F:→ wind681201: 但这就是问题,其它地方没有让_users变null的问题 09/10 15:08
11F:→ wind681201: 都是在add,就算remove key也不会让_users变null 09/10 15:09
12F:→ wind681201: 而且在新增时,我检查过一次_users是不是null了 09/10 15:10
13F:→ gn1943141: readonly 09/10 15:56
14F:→ gn1943141: 一定有什麽地方赋空值,private跟static没保证不能赋 09/10 15:59
15F:→ gn1943141: 值,可能是时序问题导致 09/10 15:59
16F:→ gn1943141: 或null的是user而不是users,确认看看 09/10 16:02
17F:→ t64141: 有没有可能 _user 是 null, 所以 _user.ID 抛错,但因为 09/10 16:16
18F:→ t64141: 位置与名字都跟 _users 太接近所以看错了? 09/10 16:16
19F:→ petercoin: @Litfal 谢谢你的指正XD 我记成C++的map了QQ 09/10 16:50
20F:→ wind681201: t64141你说的很有可能,因为重现了一样的错误 09/10 17:56
21F:→ wind681201: 我会再过滤user.id的部份,谢谢 09/10 17:56
22F:推 haves560: 注意iis 回收 可能也会导致此问题 09/13 11:56
23F:推 Litfal: iis回收会导致内容不见,但不会null,重新启动就重建 09/13 14:25
24F:→ wind681201: 我也想过IIS的问题,但是,有可能回收时,正好在执行 09/14 18:07
25F:→ wind681201: 中吗?然後会造成不见? 09/14 18:07
26F:推 kaneson: 我觉得是Add()传参数发生此_user非彼_user 09/24 09:19
27F:推 kaneson: 喔,变数名称我看错了,抱歉 09/24 09:32