当前位置:编程学习 > C#/ASP.NET >>

关于Dictionary引用的问题。

代码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);
}

这是为什么。。。。 --------------------编程问答-------------------- 贴的代码不全,你贴的FillCache只有2个参数,应该还有别的重载形式。
猜测是你应该加上ref,否则classifyDic不会指向你新产生的字典对象。 --------------------编程问答-------------------- 加上ref就可以了:
private static void FillCache(string type, string code, ref Dictionary<string, string> dic)

资料:
看看ref 关键字
http://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx --------------------编程问答-------------------- 已解决。。。
这个被人称为月经贴了。。。。
http://blog.csdn.net/vrhero/article/details/5166278
补充:.NET技术 ,  ASP.NET
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,