关于Dictionary引用的问题。

失落的code 失落的code 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
代码1:

private static Dictionary<string, string> classifyDic;
public static string GetClassifyByCode(string code)
{
string retVal;
FillCache(Constants.COMMON_TYPE_CLASSIFY, code, classifyDic);
classifyDic.TryGetValue(code, out retVal);
return retVal;
}

private static void FillCache(string type, string code, Dictionary<string, string> dic)
{
MongoDBContext<CommonCode> dbContext = new MongoDBContext<CommonCode>();
List<CommonCode> codeList = dbContext.List(model => model.CodeType == type && model.Code == code);
dic = codeList.ToDictionary(model => model.Code, model => model.CodeName1);
}

上面的代码会引发空指针,在FillCache方法中dic不是null,但是回到GetClassfyByCode方法之后就变成null了。下面的代码就没有问题。
代码2:

private static Dictionary<string, string> classifyDic;
public static string GetClassifyByCode(string code)
{
string retVal;
classifyDic = FillCache(Constants.COMMON_TYPE_CLASSIFY, code);
classifyDic.TryGetValue(code, out retVal);
return retVal;
}

private static Dictionary<string, string> FillCache(string type, string code)
{
MongoDBContext<CommonCode> dbContext = new MongoDBContext<CommonCode>();
List<CommonCode> codeList = dbContext.List(model => model.CodeType == type && model.Code == code);
return codeList.ToDictionary(model => model.Code, model => model.CodeName1);
}

这是为什么。。。。
...全文
评论 3
收藏 已收藏
分享
返回顶部
失落的code
.NET社区 62,275 成员 668,967 内容