关于Dictionary引用的问题。

失落的code 2012-11-25 01:53:50
代码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);
}

这是为什么。。。。
...全文
171 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
rayaspnet 2012-11-25
  • 打赏
  • 举报
回复
加上ref就可以了: private static void FillCache(string type, string code, ref Dictionary<string, string> dic) 资料: 看看ref 关键字 http://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx
失落的code 2012-11-25
  • 打赏
  • 举报
回复
已解决。。。 这个被人称为月经贴了。。。。 http://blog.csdn.net/vrhero/article/details/5166278
devmiao 2012-11-25
  • 打赏
  • 举报
回复
贴的代码不全,你贴的FillCache只有2个参数,应该还有别的重载形式。 猜测是你应该加上ref,否则classifyDic不会指向你新产生的字典对象。

62,244

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧