C#转换与解析

时间:2020-03-05 18:53:06  来源:igfitidea点击:

这对某些人来说似乎是基本的,但是这个问题一直困扰着我,当我编写一些代码时,我想我会问。

以下哪项是cand中更好的代码,为什么?

((DateTime)g[0]["MyUntypedDateField"]).ToShortDateString()

或者

DateTime.Parse(g[0]["MyUntypedDateField"].ToString()).ToShortDateString()

归根结底,是更好地投射还是解析?谢谢大家!

解决方案

回答

如果g [0] [" MyUntypedDateField"]实际上是一个DateTime对象,则强制转换是更好的选择。如果不是真正的DateTime,那么我们别无选择,只能使用Parse(如果尝试使用强制类型转换,则会收到InvalidCastException)

回答

正如@Brian R. Bondy指出的,它取决于g [0] [" MyUntypedDateField"]的实现。安全的做法是使用DateTime.TryParse和as运算符。

回答

解析需要一个字符串作为输入,转换需要一个对象,因此在上面提供的第二个示例中,我们需要执行两次转换:一次从对象到字符串,然后从字符串到DateTime。第一个没有。

但是,如果在执行强制转换时有发生异常的风险,则我们可能希望走第二条路线,以便可以使用TryParse并避免引发昂贵的异常。否则,采用最有效的方法,只进行一次转换(从对象到DateTime),而不要进行两次转换(从对象到字符串再到DateTime)。

回答

在http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx中可以比较不同的技术。

回答

铸造是唯一的好答案。

我们必须记住,在某些情况下,当我们无法安全地在这两个函数之间往返时,ToString和Parse结果并不总是准确的。

ToString的文档说,它使用当前的线程区域性设置。 Parse的文档说,它还使用当前的线程区域性设置(到目前为止,它们都使用相同的区域性),但是有一个明确的说明:

Formatting is influenced by properties of the current DateTimeFormatInfo object, which by default are derived from the Regional and Language Options item in Control Panel. One reason the Parse method can unexpectedly throw FormatException is if the current DateTimeFormatInfo.DateSeparator and DateTimeFormatInfo.TimeSeparator properties are set to the same value.

因此,取决于用户设置,ToString / Parse代码可能并且将意外失败...

回答

代码建议该变量可以是日期,也可以是看起来像日期的字符串。我们可以简单地使用强制类型转换返回日期,但是必须分析字符串。解析带有两个警告:

  • 如果不确定是否可以解析此字符串,则使用DateTime.TryParse()
  • 始终包含对要解析为的文化的引用。 ToShortDateString()在不同的地方返回不同的输出。我们几乎肯定会希望使用相同的语言进行解析。我建议使用此功能处理两种情况。
private DateTime ParseDateTime(object data)
{
    if (data is DateTime)
    {
        // already a date-time.
        return (DateTime)data;
    }
    else if (data is string)
    {
        // it's a local-format string.
        string dateString = (string)data;
        DateTime parseResult;
        if (DateTime.TryParse(dateString, CultureInfo.CurrentCulture,
                              DateTimeStyles.AssumeLocal, out parseResult))
        {
            return parseResult;
        }
        else
        {
            throw new ArgumentOutOfRangeException("data", 
                               "could not parse this datetime:" + data);
        }
    }
    else
    {
        // it's neither a DateTime or a string; that's a problem.
        throw new ArgumentOutOfRangeException("data", 
                              "could not understand data of this type");
    }
}

然后像这样打电话;

ParseDateTime(g[0]["MyUntypedDateField").ToShortDateString();

请注意,不良数据会引发异常,因此我们需要捕获该异常。

还; " as"运算符不适用于DateTime数据类型,因为它仅适用于引用类型,并且DateTime是一种值类型。