C# 铸造与解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/61733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 10:20:33  来源:igfitidea点击:

C# Casting vs. Parse

提问by John Virgolino

Which of the following is better code in c# and why?

以下哪个是 c# 中更好的代码,为什么?

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

or

或者

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

Ultimately, is it better to cast or to parse?

最终,是转换还是解析更好?

采纳答案by Wilka

If g[0]["MyUntypedDateField"] is really a DateTime object, then the cast is the better choice. If it's not really a DateTime, then you have no choice but to use the Parse (you would get an InvalidCastException if you tried to use the cast)

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

回答by aku

As @Brian R. Bondy pointed it depends on implementation of g[0]["MyUntypedDateField"]. Safe practice is to use DateTime.TryParseand asoperator.

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

回答by Ryan Farley

Parse requires a string for input, casting requires an object, so in the second example you provide above, then you are required to perform two casts: one from an object to a string, then from a string to a DateTime. The first does not.

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

However, if there is a risk of an exception when you perform the cast, then you might want to go the second route so you can TryParse and avoid an expensive exception to be thrown. Otherwise, go the most efficient route and just cast once (from object to DateTime) rather than twice (from object to string to DateTime).

但是,如果在执行强制转换时存在异常风险,那么您可能想要走第二条路线,这样您就可以 TryParse 并避免抛出代价高昂的异常。否则,走最有效的路线,只投射一次(从对象到 DateTime)而不是两次(从对象到字符串到 DateTime)。

回答by sgwill

There's comparison of the different techniques at http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx.

http://blogs.msdn.com/bclteam/archive/2005/02/11/371436.aspx上有不同技术的比较。

回答by qbeuek

Casting is the onlygood answer.

铸造是唯一的好答案。

You have to remember, that ToString and Parse results are not always exact - there are cases, when you cannot safely roundtrip between those two functions.

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

The documentation of ToString says, it uses current thread culture settings. The documentation of Parse says, it also uses current thread culture settings (so far so good - they are using the same culture), but there is an explicit remark, that:

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.

格式受当前 DateTimeFormatInfo 对象的属性影响,默认情况下,这些属性派生自控制面板中的区域和语言选项项。Parse 方法可能意外抛出 FormatException 的原因之一是当前 DateTimeFormatInfo.DateSeparator 和 DateTimeFormatInfo.TimeSeparator 属性设置为相同的值。

So depending on the users settings, the ToString/Parse code can and will unexpectedly fail...

因此,根据用户设置,ToString/Parse 代码可能并且会意外失败......

回答by Steve Cooper

Your code suggests that the variable may be either a date or a string that looks like a date. Dates you can simply return wit a cast, but strings must be parsed. Parsing comes with two caveats;

您的代码表明该变量可以是日期或看起来像日期的字符串。您可以简单地通过转换返回日期,但必须解析字符串。解析有两个警告;

  1. if you aren't certain this string can be parsed, then use DateTime.TryParse().

  2. Always include a reference to the culture you want to parse as. ToShortDateString()returns different outputs in different places. You will almost certainly want to parse using the same culture. I suggest this function dealing with both situations;

    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");
        }
    }
    
  1. 如果您不确定可以解析此字符串,请使用DateTime.TryParse().

  2. 始终包含对要解析为的文化的引用。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");
        }
    }
    

Then call like this;

然后这样调用;

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

Note that bad data throws an exception, so you'll want to catch that.

请注意,错误数据会引发异常,因此您需要捕获该异常。

Also; the 'as' operator does not work with the DateTime data type, as this only works with reference types, and DateTime is a value type.

还; “as”运算符不适用于 DateTime 数据类型,因为这只适用于引用类型,而 DateTime 是一种值类型。