c# - 尝试并捕获 block 。哪种解决方案更好

标签 c# design-patterns try-catch

对我来说,这似乎是一个合理的模式:

int.TryParse()

和简单的 if,而不是:
int.Parse()

在 try block 内。直到我在 MS 模式和实践中找到了这个样本
    /// <summary>
    /// Update a setting value for our application. If the setting does not
    /// exist, then add the setting.
    /// </summary>
    /// <param name="Key"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool AddOrUpdateValue(string Key, Object value)
    {
        bool valueChanged = false;
        try
        {
            // if new value is different, set the new value.
            if (isolatedStore[Key] != value)
            {
                isolatedStore[Key] = value;
                valueChanged = true;
            }
        }
        catch (KeyNotFoundException)
        {
            isolatedStore.Add(Key, value);
            valueChanged = true;
        }
        catch (ArgumentException)
        {
            isolatedStore.Add(Key, value);
            valueChanged = true;
        }
        catch (Exception e)
        {
            Debug.WriteLine("Exception while using IsolatedStorageSettings: " + e.ToString());
        }

        return valueChanged;
    }

使用包含方法不是更好吗?另一方面,我读到 CLR 可以将 try-catch 优化为简单的 goto。

最佳答案

是的,不要为此使用 catch block 。我不确定您在哪里找到该代码,但我怀疑它非常古老。 Contains() 方法要快得多。此外,请查看 TryGetValue () 字典类的方法。

关于c# - 尝试并捕获 block 。哪种解决方案更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3611613/

相关文章:

c# - FastColoredTextbox AutoWordSelection?

android - 在 build.gradle 中找不到构建工具修订版 25.0.0 rc1

c# - try catch block

r - R 中 foreach() 内的 try() 问题

c# - 与互联网断开连接时卡在 UploadFromStream 中

c# - 如何制作仅包含一组自身类型或子类型的泛型类作为子类?

c# - Entity Framework 、linq 函数和内存使用

c# - 如何在 net-core 2.0 中手动解析 JSON 字符串

java - 单例方法线程安全

unit-testing - 单元测试模式