读书人

C# Dictionarylt;string,objectgt;遇到的有

发布时间: 2012-03-30 17:32:10 作者: rapoo

求助:C# Dictionary<string,object>遇到的问题。
异常描述:

System.ArgumentNullException: Value cannot be null.
Parameter name: key
at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.ContainsKey(TKey key)

C# code
        public static void CloneKeyTo(ASObject sourceASO, out ASObject desASO)        {            desASO = new ASObject();            string[] keys;            lock (sourceASO.Keys)            {                keys = sourceASO.Keys.ToArray();            }            foreach (string key in keys)            {                lock (sourceASO)                {                    if (sourceASO.ContainsKey(key))//这里出异常,说key==null                    {                        desASO[key] = sourceASO[key];                    }                }            }        }


测试代码:

C# code
Dictionary<string,object> demoObj = new Dictionary<string,object>();demoObj[null]=1;//这是更加不可能的,直接异常。


我想问一下:什么情况下,Dictionary<string,object>中,的Keys的元素,中,会有子元素,有可能为:null的情况?

而这个Keys是只读的属性。

[解决办法]
foreach (string key in keys)
{
lock (sourceASO)
{
string strKey=key;
if (strKey==null)
{ strKey="";
}
if (sourceASO.ContainsKey(strKey))//这里出异常,说key==null
{
desASO[strKey] = sourceASO[strKey];
}
}
}

读书人网 >C#

热点推荐