在对象初始化中尝试Catch

时间:2016-10-01 17:25:15

标签: c#

我正在阅读包含日期归档的CSV文件 如何在尝试转换为DateTime时忽略异常?

        var csvlines = File.ReadAllLines(FilePath);    
        // skip the first line!
        var csvLinesData = csvlines.Skip(1).Select(l => l.Split(Consts.Delimiter)); 

        return csvLinesData.Select(data => new ReleaseNote
        {
            Version = data[0],
            ReleaseDate = Convert.ToDateTime(data[1]) // Possible exception

        }).ToList();

2 个答案:

答案 0 :(得分:4)

public class Pair 
{

  private int left;
  private int right;

  public Pair(int left, int right) {
    // the following 2 lines don't do anything
    // it set's the argument "left = left" which is silly...

    left = left;
    right = right;

    // with the `this` keyword we can correctly initialize our class properties
    // and avoid name collision

    this.left = left;
    this.right = right;
  }

}

如果您的ReleaseDate属性可以为空,您也可以放置return csvLinesData.Select(data => { DateTime d; return new ReleaseNote { Version = data[0], ReleaseDate = DateTime.TryParse(data[1], out d) ? d : DateTime.MinValue } }).ToList(); 而不是null

答案 1 :(得分:1)

你应该使用DateTime.TryParse:

https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx

foreach (string dateString in dateStrings)
  {
     if (DateTime.TryParse(dateString, out dateValue)) 
        Console.WriteLine("  Converted '{0}' to {1} ({2}).", dateString, 
                          dateValue, dateValue.Kind);
     else
        Console.WriteLine("  Unable to parse '{0}'.", dateString);
  }