对我来说,这似乎是一个合理的模式:
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/