日期:2014-05-18  浏览次数:20832 次

关于"并非所有路径都返回值"
我想让日期函数识别 "20081101" 这样的日期格式.
在下面的代码中:
C# code

    class myDateTimea
    {
        public static DateTime Parse(string s)
        {
            if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
                s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
            try
            {
                return DateTime.Parse(s);
            }
            catch
            {
              //日期格式不正确
                //return null;
            }
        }
    }


如果在 catch 里不写返回语句,会提示:"并非所有路径都返回值"
如果加 return null,会提示:"错误 1 无法将 NULL 转换成“System.DateTime”,因为它是一种值类型"

如果加的话,不知道加个什么返回值.
这样的问题该如何解决?
谢谢大家?

------解决方案--------------------
这里的逻辑似乎是,如果能parse成功就返回,不能成功就抛出异常吧~~
然后使用这个方法的代码再对异常进行处理
try
{
return DateTime.Parse(s);
}
catch
{
//日期格式不正确
throw new ArgumentException("Invalid input string");
}

------解决方案--------------------
把返回类型DataTime 改成 DateTime?
下面就可以正确运行了。
class myDateTimea
{
public static DateTime? Parse(string s)
{
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
return DateTime.Parse(s);
}
catch
{
return null;
}
}
}
------解决方案--------------------
非要返回null的话这样做吧
public static DateTime? Parse(string s)
{
DateTime? dt = null; 
if (s.Length == 8 && s.IndexOfAny(new char[] { '-', '/' }) == -1)
s = s.Substring(0, 4) + "-" + s.Substring(4, 2) + "-" + s.Substring(6, 2);
try
{
dt = DateTime.Parse(s);
return dt;
}
catch
{
//日期格式不正确
return dt;
}
}
------解决方案--------------------
探讨
return DateTime.MinValue;
另外,要识别"20081101"这种格式不用这么麻烦的

C# code
string str = "20081101";
DateTime dt = DateTime.ParseExact(str, "yyyyMMdd", null);