如果 ConvertAll 在一个元素上抛出异常,我可以跳过这个元素并继续下一个元素吗?
最佳答案
没有。异常需要在某处处理。如果您希望转换器中发生异常(这对应用程序来说是可以的),您必须在转换器中有一个 try-catch(以下代码示例将为失败的转换返回 null
):
List<string> input = new List<string> { "1", "2", "three", "4" };
List<int?> converted = input.ConvertAll(s =>
{
int? result = null;
try
{
result = int.Parse(s);
}
catch (Exception) { }
return result;
});
(是的,我知道我应该使用 int.TryParse
,但这不会引发异常...)
但是,像这样吃异常总是给人一种解决方法的味道,这不是我希望在我的代码中包含的东西。
关于c# - List.ConvertAll 和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585789/