C# - 常见问题整理

时间:2019-09-19
本文章向大家介绍C# - 常见问题整理,主要包括C# - 常见问题整理使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

关于循环和try{}..catch{}的嵌套使用

foreach(var item in items) {
    try {
        try{
        } catch(Exception ex) {
            throw; // 将异常抛到外层(要根据实际情况,决定是否throw)
        }    
    } catch(Exception ex) {
        continue; // or break; or return false; 视情况而定
    }
}

关于集合类的遍历操作问题

ConcurrentDictionary<string, string> ResDicCon = new ConcurrentDictionary<string, string>();
ResDicCon.TryAdd("0", "000"); ResDicCon.TryAdd("1", "111"); ResDicCon.TryAdd("2", "222"); ResDicCon.TryAdd("3", "333");
foreach (string key in ResDicCon.Keys) {
    string Str = null;  // ConcurrentDictionary遍历时,删除key是没问题的
    ResDicCon.TryRemove(key, out Str);
}
 
Dictionary<string, string> ResDic = new Dictionary<string, string>();
ResDic.Add("0", "000"); ResDic.Add("1", "111"); ResDic.Add("2", "222"); ResDic.Add("3", "333");
foreach (string key in ResDic.Keys) {
    // Dictionary遍历时,删除key会报错
    ResDic.Remove(key); // ResDic["2"] = "66"; 更改也会报错
}

Dictionary在foreach时,不支持删除或更改数据,否则:未处理 InvalidOperationException 集合已修改;可能无法执行枚举操作

原文地址:https://www.cnblogs.com/wjcx-sqh/p/11552693.html