本文整理匯總了C#中System.Collections.Specialized.StringDictionary.Clear方法的典型用法代碼示例。如果您正苦於以下問題:C# StringDictionary.Clear方法的具體用法?C# StringDictionary.Clear怎麽用?C# StringDictionary.Clear使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類System.Collections.Specialized.StringDictionary
的用法示例。
在下文中一共展示了StringDictionary.Clear方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: ReadMap
private static void ReadMap(StringDictionary map, TextReader reader, string mapName)
{
map.Clear();
var mappings = reader.ReadLine().Replace(string.Format("{0}:", mapName), string.Empty).Split(new[] {';'},
StringSplitOptions.
RemoveEmptyEntries);
foreach (string mapping in mappings)
{
string[] parts = mapping.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
map.Add(parts[0], parts[1]);
}
}
示例2: Main
public static void Main()
{
// Creates and initializes a new StringDictionary.
StringDictionary myCol = new StringDictionary();
myCol.Add("red", "rojo");
myCol.Add("green", "verde");
myCol.Add("blue", "azul");
Console.WriteLine("Count: {0}", myCol.Count);
// Display the contents of the collection using foreach. This is the preferred method.
Console.WriteLine("Displays the elements using foreach:");
PrintKeysAndValues1(myCol);
// Display the contents of the collection using the enumerator.
Console.WriteLine("Displays the elements using the IEnumerator:");
PrintKeysAndValues2(myCol);
// Display the contents of the collection using the Keys, Values, Count, and Item properties.
Console.WriteLine("Displays the elements using the Keys, Values, Count, and Item properties:");
PrintKeysAndValues3(myCol);
// Copies the StringDictionary to an array with DictionaryEntry elements.
DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count];
myCol.CopyTo(myArr, 0);
// Displays the values in the array.
Console.WriteLine("Displays the elements in the array:");
Console.WriteLine(" KEY VALUE");
for (int i = 0; i < myArr.Length; i++)
Console.WriteLine(" {0,-10} {1}", myArr[i].Key, myArr[i].Value);
Console.WriteLine();
// Searches for a value.
if (myCol.ContainsValue("amarillo"))
Console.WriteLine("The collection contains the value \"amarillo\".");
else
Console.WriteLine("The collection does not contain the value \"amarillo\".");
Console.WriteLine();
// Searches for a key and deletes it.
if (myCol.ContainsKey("green"))
myCol.Remove("green");
Console.WriteLine("The collection contains the following elements after removing \"green\":");
PrintKeysAndValues1(myCol);
// Clears the entire collection.
myCol.Clear();
Console.WriteLine("The collection contains the following elements after it is cleared:");
PrintKeysAndValues1(myCol);
}
示例3: Empty
public void Empty ()
{
StringDictionary sd = new StringDictionary ();
Assert.AreEqual (0, sd.Count, "Count");
Assert.IsFalse (sd.IsSynchronized, "IsSynchronized");
Assert.AreEqual (0, sd.Keys.Count, "Keys");
Assert.AreEqual (0, sd.Values.Count, "Values");
Assert.IsNotNull (sd.SyncRoot, "SyncRoot");
Assert.IsFalse (sd.ContainsKey ("a"), "ContainsKey");
Assert.IsFalse (sd.ContainsValue ("1"), "ContainsValue");
sd.CopyTo (new DictionaryEntry[0], 0);
Assert.IsNotNull (sd.GetEnumerator (), "GetEnumerator");
sd.Remove ("a"); // doesn't exists
sd.Clear ();
}
示例4: SetEnvironment
/// <summary>
/// Copy elements from a Python mapping of dict environment variables to a StringDictionary.
/// </summary>
private static void SetEnvironment(StringDictionary currentEnvironment, object newEnvironment)
{
Dict env = newEnvironment as Dict;
if (env == null) {
throw Ops.TypeError("env argument must be a dict");
}
currentEnvironment.Clear();
string strKey, strValue;
foreach (object key in env.Keys) {
if (!Converter.TryConvertToString(key, out strKey)) {
throw Ops.TypeError("env dict contains a non-string key");
}
if (!Converter.TryConvertToString(env[key], out strValue)) {
throw Ops.TypeError("env dict contains a non-string value");
}
currentEnvironment[strKey] = strValue;
}
}
示例5: Test01
public void Test01()
{
IntlStrings intl;
StringDictionary sd;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0;
// initialize IntStrings
intl = new IntlStrings();
// [] StringDictionary is constructed as expected
//-----------------------------------------------------------------
sd = new StringDictionary();
// [] Remove() from empty dictionary
//
if (sd.Count > 0)
sd.Clear();
for (int i = 0; i < keys.Length; i++)
{
sd.Remove(keys[0]);
}
// [] Remove() from filled dictionary
//
int len = values.Length;
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, len));
}
for (int i = 0; i < len; i++)
{
cnt = sd.Count;
sd.Remove(keys[i]);
if (sd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, didn't remove element with {0} key", i));
}
// verify that indeed element with given key was removed
if (sd.ContainsValue(values[i]))
{
Assert.False(true, string.Format("Error, removed wrong value", i));
}
if (sd.ContainsKey(keys[i]))
{
Assert.False(true, string.Format("Error, removed wrong value", i));
}
}
//
// [] Remove() on dictionary with identical values
//
sd.Clear();
string intlStr = intl.GetRandomString(MAX_LEN);
sd.Add("keykey1", intlStr); // 1st duplicate
for (int i = 0; i < len; i++)
//.........這裏部分代碼省略.........
示例6: SomeElements
public void SomeElements ()
{
StringDictionary sd = new StringDictionary ();
for (int i = 0; i < 10; i++)
sd.Add (i.ToString (), (i * 10).ToString ());
Assert.AreEqual ("10", sd["1"], "this[1]");
Assert.AreEqual (10, sd.Count, "Count-10");
Assert.AreEqual (10, sd.Keys.Count, "Keys");
Assert.AreEqual (10, sd.Values.Count, "Values");
Assert.IsTrue (sd.ContainsKey ("2"), "ContainsKey");
Assert.IsTrue (sd.ContainsValue ("20"), "ContainsValue");
DictionaryEntry[] array = new DictionaryEntry[10];
sd.CopyTo (array, 0);
sd.Remove ("1");
Assert.AreEqual (9, sd.Count, "Count-9");
sd.Clear ();
Assert.AreEqual (0, sd.Count, "Count-0");
}
示例7: Test01
//.........這裏部分代碼省略.........
// access the item
//
ind = intlValues[i + len];
if (String.Compare(sd[ind], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]));
}
}
//
// add null string with non-null key
// [] add null string with non-null key and verify ContainsKey()
//
cnt = sd.Count;
string k = "keykey";
sd.Add(k, null);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", sd.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (!sd.ContainsKey(k))
{
Assert.False(true, string.Format("Error, dictionary doesn't contain new key"));
}
//
// [] Case sensitivity: search should be case-sensitive
//
sd.Clear();
if (sd.Count != 0)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2} after Clear()", sd.Count, 0));
}
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
sd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = sd.Count;
sd.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (!sd.ContainsValue(intlValues[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
}
if (!sd.ContainsKey(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i]))
{
Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i));
}
// key is case insensitive
if (!sd.ContainsKey(intlValuesLower[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i));
}
}
//
// call ContainsKey with null - ArgumentNullException expected
// [] ContainsKey (null)
//
Assert.Throws<ArgumentNullException>(() => { sd.ContainsKey(null); });
}
示例8: CleanEnvironmentVariables
private static void CleanEnvironmentVariables(StringDictionary variables)
{
variables.Clear();
variables[EnvironmentSystemDrive] = System.Environment.GetEnvironmentVariable(EnvironmentSystemDrive);
variables[EnvironmentSystemRoot] = System.Environment.GetEnvironmentVariable(EnvironmentSystemRoot);
variables[EnvironmentPath] = System.Environment.SystemDirectory;
variables[EnvironmentTemp] = System.Environment.GetEnvironmentVariable(EnvironmentTemp);
}
示例9: setSQLTableDefaults
public void setSQLTableDefaults(string table, ref StringDictionary sql)
{
//sql = new StringDictionary();
sql.Clear();
if (table == "SCAPersona")
{
// Setting SCAPersona defaults
sql.Add("Tipo","2");
sql.Add("Referencia", "NULL");
sql.Add("Apellido1", "NULL");
sql.Add("Apellido2", "NULL");
// Field fields (not used)
foreach (string key in field_keys)
{
sql.Add(key, "NULL");
}
// Alta
sql.Add("Alta", DateTime.Now.ToString ("yyyyMMdd HH:mm"));
}
else if (table == "SCAMuestra")
{
string data = DateTime.Now.ToString("yyyyMMdd");
string hora = DateTime.Now.ToShortTimeString();
// Setting SCAMuestra defaults
sql.Add("IdEspecie", "NULL");
sql.Add("IdCentro", "1");
sql.Add("IdDoctor", "1");
sql.Add("FechaAnalisis", data);
sql.Add("HoraAnalisis", hora);
sql.Add("Volumen", "2.5");
sql.Add("FechaObtencion", data);
sql.Add("HoraObtencion", hora);
sql.Add("HoraEntrega", hora);
sql.Add("IdMetodoObtencion", "1");
sql.Add("DiasAbstinencia", "3");
sql.Add("pH", "7.5");
sql.Add("Temperatura", "37");
sql.Add("IdColor", "1");
sql.Add("IdViscosidad", "1");
sql.Add("IdLicuefaccion", "1");
sql.Add("IdAspecto", "1");
sql.Add("IdOlor", "1");
sql.Add("IdAglutinaciones", "1");
sql.Add("IdOtrasPropiedades", "1");
sql.Add("Observaciones", "NULL");
sql.Add("local", "1");
sql.Add("Other", "NULL");
sql.Add("Confirmed", "0");
sql.Add("IdCollection1", "1");
sql.Add("IdCollection2", "1");
// Optional fields (not used)
foreach (string key in optional_keys)
{
sql.Add(key, "NULL");
}
}
}
示例10: fromXLStoSQL
//.........這裏部分代碼省略.........
// Logger.Debug("Found " + numColumns + " columns in excel file");
if (numColumns < 2 || numColumns > 3)
{
// file format not supported
excelReader.Close();
stream.Close();
return false;
}
string [] columns = new string [numColumns];
try
{
for (int i=0; i<numColumns; i++)
{
columns[i] = excelReader.GetString(i);
// Logger.Debug("Column " + i.ToString() + ": " + columns[i]);
}
}
catch(Exception e)
{
Logger.Fatal("Can't read xls file: " + e.ToString());
excelReader.Close();
stream.Close();
return false;
}
string nom = null;
string nhc = null;
string referencia = null;
if (numColumns >= 3)
{
referencia = columns[0];
nhc = columns[1];
nom = columns[2];
}
else
{
nhc = columns[0];
nom = columns[1];
}
if (nom != null && nhc != null)
{
StringDictionary sql = new StringDictionary();
setSQLTableDefaults("SCAPersona", ref sql);
sql.Add("Nombre", nom);
sql.Add("Nombre1", nom);
sql.Add("NHC", nhc);
int lastInsertRowId = -1;
if (storeSQL("SCAPersona", sql, ref lastInsertRowId) == false)
{
excelReader.Close();
stream.Close();
return false;
}
if (numColumns >= 3 && referencia != null && lastInsertRowId != -1)
{
/*
Si el xls té tres columnes, a part d’emplenar
la taula SCAPersona tal i com ja ho fa,
hauries d’emplenar també la taula SCAMuestra
on la primera columna seria la referencia de la mostra.
Tots els altres camps de SCAMuestra els hauries de posar
amb un valor per defecte
*/
sql.Clear();
setSQLTableDefaults("SCAMuestra", ref sql);
sql.Add("Referencia", referencia);
sql.Add("IdPersona", lastInsertRowId.ToString());
if (storeSQL("SCAMuestra", sql) == false)
{
excelReader.Close();
stream.Close();
return false;
}
}
}
else
{
Logger.Debug("Empty fields or wrong number of them. Going to next row.");
}
}
excelReader.Close();
stream.Close();
return true;
}
示例11: Test01
//.........這裏部分代碼省略.........
}
if (!sd.ContainsKey(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
ind = intlValues[i + len];
if (String.Compare(sd[ind], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
sd.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = sd.Count;
sd.Add(intlValues[i + len], intlValues[i]);
if (sd.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (!sd.ContainsValue(intlValues[i]))
{
Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i));
}
if (!sd.ContainsKey(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i]))
{
Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i));
}
示例12: Test01
public void Test01()
{
IntlStrings intl;
StringDictionary sd;
// simple string values
string[] values =
{
"",
" ",
"a",
"aa",
"text",
" spaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"one",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] StringDictionary is constructed as expected
//-----------------------------------------------------------------
sd = new StringDictionary();
cnt = sd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after default ctor", sd.Count, 0));
}
// [] Clear() empty dictionary
//
sd.Clear();
cnt = sd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", sd.Count, 0));
}
// [] Add simple strings and Clear()
//
cnt = sd.Count;
for (int i = 0; i < values.Length; i++)
{
sd.Add(keys[i], values[i]);
}
if (sd.Count != values.Length)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
}
sd.Clear();
cnt = sd.Count;
if (cnt != 0)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1} after Clear()", sd.Count, 0));
}
//
// [] Add Intl strings and Clear()
//
int len = values.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
// Add items
//
cnt = sd.Count;
//.........這裏部分代碼省略.........
示例13: SetTeamChangeSQL
//.........這裏部分代碼省略.........
// }
// }
// catch (Exception exp)
// { //返回錯誤消息
// }
// return flag;
//}
/// <summary>
/// 人員調動數據更新
/// </summary>
/// <param name="AttendDate"></param>
/// <param name="JobForID"></param>
/// <param name="ProjectID"></param>
/// <param name="LineID"></param>
/// <param name="TeamID"></param>
/// <param name="UserID"></param>
/// <param name="pFlag">調動類型</param>
/// <returns></returns>
public static int SetTeamChangeSQL(string AttendDate, string JobForID, string ProjectID, string LineID, string TeamID,string UserID,string pFlag)
{
int result = 0;
try
{
StringDictionary dicItemName = new StringDictionary();
StringDictionary dicPrimarName = new StringDictionary();
string str_sql = string.Empty;
DataTable dt_temp=new DataTable();
//刪除Attend_Total_Result表中對應UserID的信息
str_sql = string.Format(@"DELETE t1 FROM Attend_Total_Result t1 WHERE t1.AttendDate=convert(VARCHAR(10),'{0}')
AND t1.JobForID='{1}' AND t1.ProjectID='{2}' AND t1.LineID='{3}' AND t1.TeamID='{4}' AND t1.UserID='{5}'",
AttendDate, JobForID, ProjectID, LineID, TeamID, UserID);
dicItemName["AttendDate"]=AttendDate;
dicItemName["JobForID"]=JobForID;
dicItemName["ProjectID"]=ProjectID;
dicItemName["LineID"]=LineID;
dicItemName["TeamID"]=TeamID;
dicItemName["UserID"]=UserID;
dicPrimarName["AttendDate"] = "true";
dicPrimarName["JobForID"] = "true";
dicPrimarName["ProjectID"] = "true";
dicPrimarName["LineID"] = "true";
dicPrimarName["TeamID"] = "true";
dicPrimarName["UserID"] = "true";
result=SysParam.m_daoCommon.SetDeleteDataItem("Attend_Total_Result", dicItemName, dicPrimarName);
//查詢V_Attend_Move_i表的人員調動情況並且在V_Produce_User是在職人員,向別班別線別班別都相同
str_sql = string.Format(@"select distinct
H2.ID,H2.UserID,H2.UserName,H1.Sex,H2.JobForID,
H2.ProjectID,H2.LineID,H2.TeamID,H2.GuanweiID,H2.GuanweiSite ,
H2.StrDate,H2.EndDate,H2.MoveStatus,
ISNULL(H1.AttendUnit,0) AS AttendUnit,H1.StatusNames AS AttendType,'' AS AttendMemo,H1.StatusIDs,
H1.StatusNames,H2.OperID
FROM V_Attend_Move_i H2
LEFT JOIN V_Produce_User H1 --調動視圖
ON H2.UserID=H1.UserID --向別
AND H2.ProjectID=H1.ProjectID AND H2.LineID=H1.LineID AND H2.TeamID=H1.TeamID AND H1.User_Status='在職'
where 1=1
AND H2.PFlag in ('{0}')
AND CONVERT(VARCHAR(10), H2.EndDate,120) ='4000-01-01' and H2.UserID='{1}'",
pFlag,UserID);
dt_temp=SysParam.m_daoCommon.GetTableInfoBySqlNoWhere(str_sql);
if (dt_temp.Rows.Count > 0)
{
//將查詢到的V_Attend_Move_i表中的數據插入到Attend_Total_Result
dicItemName.Clear();
dicPrimarName.Clear();
dicItemName["AttendDate"] = AttendDate;
dicItemName["UserID"] = dt_temp.Rows[0]["UserID"].ToString();
dicItemName["UserNM"] = dt_temp.Rows[0]["UserNM"].ToString();
dicItemName["Sex"] = dt_temp.Rows[0]["Sex"].ToString();
dicItemName["JobForID"] = dt_temp.Rows[0]["JobForID"].ToString();
dicItemName["ProjectID"] = dt_temp.Rows[0]["ProjectID"].ToString();
dicItemName["LineID"] = dt_temp.Rows[0]["LineID"].ToString();
dicItemName["TeamID"] = dt_temp.Rows[0]["TeamID"].ToString();
dicItemName["GuanweiID"] = dt_temp.Rows[0]["GuanweiID"].ToString();
dicItemName["GuanweiSite"] = dt_temp.Rows[0]["GuanweiSite"].ToString();
dicItemName["TeamSetID"] = dt_temp.Rows[0]["TeamSetID"].ToString();
dicItemName["AttendType"] = dt_temp.Rows[0]["AttendType"].ToString();
dicItemName["AttendMemo"] = dt_temp.Rows[0]["AttendMemo"].ToString();
dicItemName["CardTime"] = "";
dicItemName["LastDate"] = "";
dicItemName["AttendWork"] = dt_temp.Rows[0]["AttendWork"].ToString();
dicItemName["StatusID"] = dt_temp.Rows[0]["StatusID"].ToString();
dicItemName["StatusName"] = dt_temp.Rows[0]["StatusName"].ToString();
dicItemName["OperID"] = dt_temp.Rows[0]["OperID"].ToString();
result = SysParam.m_daoCommon.SetInsertDataItem("Attend_Total_Result", dicItemName);
}
}
catch (Exception ex)
{
return result;
throw ex;
}
return result;
}
示例14: Test01
//.........這裏部分代碼省略.........
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
}
destination = Array.CreateInstance(typeof(Object), len);
sd.CopyTo(destination, 0);
IEnumerator en = sd.GetEnumerator();
//
// order of items is the same as order of enumerator
//
for (int i = 0; i < len; i++)
{
en.MoveNext();
// verify that collection is copied correctly
//
DictionaryEntry curr = (DictionaryEntry)en.Current;
if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i)).Value.ToString()) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Value, curr.Value));
}
if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i)).Key.ToString()) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i)).Key, curr.Key));
}
}
//
// [] add simple strings and CopyTo(Array, middle_index)
sd.Clear();
for (int i = 0; i < len; i++)
{
sd.Add(keys[i], values[i]);
}
if (sd.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, values.Length));
}
destination = Array.CreateInstance(typeof(Object), len * 2);
sd.CopyTo(destination, len);
en = sd.GetEnumerator();
//
// order of items is the same as order of enumerator
//
for (int i = 0; i < len; i++)
{
en.MoveNext();
// verify that collection is copied correctly
//
DictionaryEntry curr = (DictionaryEntry)en.Current;
if (String.Compare(curr.Value.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Value.ToString()) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Value, curr.Value));
}
if (String.Compare(curr.Key.ToString(), ((DictionaryEntry)destination.GetValue(i + len)).Key.ToString()) != 0)
{
Assert.False(true, string.Format("Error, copied \"{1}\" instead of \"{2}\"", i, ((DictionaryEntry)destination.GetValue(i + len)).Key, curr.Key));
示例15: Test01
//.........這裏部分代碼省略.........
Assert.False(true, string.Format("Error, Value for current Key is different in dictionary", i));
}
// while we didn't MoveNext, Current should return the same value
DictionaryEntry curr1 = (DictionaryEntry)en.Current;
if (!curr.Equals(curr1))
{
Assert.False(true, string.Format("Error, second call of Current returned different result", i));
}
}
// next MoveNext should bring us outside of the collection
//
res = en.MoveNext();
res = en.MoveNext();
if (res)
{
Assert.False(true, string.Format("Error, MoveNext returned true"));
}
//
// Attempt to get Current should result in exception
//
Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });
en.Reset();
//
// Attempt to get Current should result in exception
//
Assert.Throws<InvalidOperationException>(() => { curr = (DictionaryEntry)en.Current; });
//
// [] Modify dictionary when enumerating
//
if (sd.Count < 1)
{
for (int i = 0; i < values.Length; i++)
{
sd.Add(keys[i], values[i]);
}
}
en = sd.GetEnumerator();
res = en.MoveNext();
if (!res)
{
Assert.False(true, string.Format("Error, MoveNext returned false"));
}
curr = (DictionaryEntry)en.Current;
int cnt = sd.Count;
sd.Remove(keys[0]);
if (sd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
}
// will return just removed item
DictionaryEntry curr2 = (DictionaryEntry)en.Current;
if (!curr.Equals(curr2))
{
Assert.False(true, string.Format("Error, current returned different value after modification"));
}
// exception expected
Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });
//
// [] Modify dictionary when enumerated beyond the end
//
sd.Clear();
for (int i = 0; i < values.Length; i++)
{
sd.Add(keys[i], values[i]);
}
en = sd.GetEnumerator();
for (int i = 0; i < sd.Count; i++)
{
en.MoveNext();
}
curr = (DictionaryEntry)en.Current;
curr = (DictionaryEntry)en.Current;
cnt = sd.Count;
sd.Remove(keys[0]);
if (sd.Count != cnt - 1)
{
Assert.False(true, string.Format("Error, didn't remove item with 0th key"));
}
// will return just removed item
curr2 = (DictionaryEntry)en.Current;
if (!curr.Equals(curr2))
{
Assert.False(true, string.Format("Error, current returned different value after modification"));
}
// exception expected
Assert.Throws<InvalidOperationException>(() => { res = en.MoveNext(); });
}