简体   繁体   English

C#:我什么时候应该使用TryParse?

[英]C#: When should I use TryParse?

I understand it doesn't throw an Exception and because of that it might be sightly faster, but also, you're most likely using it to convert input to data you can use, so I don't think it's used so often to make that much of difference in terms of performance. 我知道它不会抛出异常,因为它可能会快得多,而且,你最有可能用它来将输入转换成你可以使用的数据,所以我不认为它经常被用来制作在性能方面有很大差异。

Anyway, the examples I saw are all along the lines of an if/else block with TryParse , the else returning an error message. 无论如何,我看到的示例都是使用TryParse的if / else块的行,else返回错误消息。 And to me, that's basically the same thing as using a try/catch block with the catch returning an error message. 对我来说,这与使用try / catch块并返回错误消息的catch基本相同。

So, am I missing something? 那么,我错过了什么吗? Is there a situation where this is actually useful? 是否存在实际有用的情况?

Apart from the performance aspect that you mentioned yourself, there's also a semantic difference: 除了你自己提到的性能方面,还有一个语义差异:

Using try/catch is meant for exceptional circumstances. 使用try / catch是出于特殊情况。 Inputting invalid data is something you expect, not something exceptional. 输入无效数据是您期望的,而不是特殊的。

It's pretty much as simple as this: Use Parse if you want an exception when you encounter invalid data; 它就像这样简单:如果在遇到无效数据时需要异常,请使用Parse ; use TryParse if you don't. 如果不这样做,请使用TryParse Your question seems, therefore, to be: 因此,你的问题似乎是:

Why would you not want an exception if data is invalid? 如果数据无效,为什么不想要例外?

Exceptions should only be used for exceptional cases, and the data being invalid might not be an exceptional case. 例外情况仅应用于例外情况,而无效的数​​据可能不是例外情况。 Maybe you're writing a data cleansing program that's expecting to get invalid data and will try to infer what a reasonable value is when the data is invalid. 也许你正在编写一个数据清理程序,它希望获得无效数据,并试图在数据无效时推断出合理的值。 Maybe the data isn't all that important and you can just skip the record that contains it. 也许数据并不那么重要,你可以跳过包含它的记录。

It depends on context, and having the choice of Parse and TryParse methods lets you choose the appropriate parsing mechanism for yours. 它取决于上下文,并且选择ParseTryParse方法可以为您选择适当的解析机制。

在可能的情况下,使用TryParse - 使用它比抛出异常要便宜得多。

Suppose you're reading a log file: 假设您正在读取日志文件:

public IEnumerable<LogEntry> GetAllValidEntries() {
    while (!logReader.Finished) {
        string nextLine = logReader.ReadLine();
        LogEntry nextEntry;

        if (TryParseLogEntry(nextLine, out nextEntry))
            yield return nextEntry;
    }
}

private bool TryParseLogEntry(string line, out LogEntry logEntry) {
    logEntry = null;

    if (string.IsNullOrEmpty(line))
        return false;

    string[] cells = line.Split(';');
    if (cells.Length < 3)
        return false;

    DateTime time;
    decimal price;
    int quantity;

    // We just want to read this line of text as a LogEntry
    // IF it is valid; otherwise, there's no reason to throw
    // an error in the user's face
    if (!DateTime.TryParse(cells[0], out time) ||
        !decimal.TryParse(cells[1], out price) ||
        !int.TryParse(cells[2], out quantity))
        return false;

    logEntry = new LogEntry(time, price, quantity);
    return true;
}

Since the whole purpose of the above code is to extract valid items from a sequence (which is presumably expected to contain some invalid items), I think TryParse methods make a lot more sense in this case than Parse methods, which demand valid input. 由于上述代码的整个目的是提取序列有效的项目(这大概是预期包含一些无效的项目),我想TryParse方法,在这种情况下不是使很多更有意义Parse方法,这需要有效的输入。

如果您需要在解析失败时设置默认值,TryParse和if是一种很好的方法。

Well int.TryParse returns a bool allowing you to test if it was successful instead of catching an exception. 那么int.TryParse返回一个bool,允许你测试它是否成功而不是捕获异常。 I usually use it in situations where if the information was successfully translated, I want to use it, but if not, it's not important, I can ignore the failure in-so-far as I want to use a default unless I get a meaningful value in which case I'll override it, but if the value wasn't meaningful, I'll keep the default. 我通常在信息被成功翻译的情况下使用它,我想使用它,但如果没有,它并不重要,我可以忽略失败,因为我想使用默认值,除非我得到一个有意义的值,在这种情况下我会覆盖它,但如果值没有意义,我将保持默认值。

The theory says that exceptions are inherently expensive, and thus you shouldn't use them to dictate program flow. 该理论认为异常本质上是昂贵的,因此你不应该用它们来决定程序流程。 You should catch them where something is semantically wrong, rather than something that may be interpreted as data flow. 您应该在语义错误的地方捕获它们,而不是可能被解释为数据流的东西。

对于不介意在失败的解析(可能是无效的输入)上设置值为0或需要简洁的情况的情况,TryParse的返回码允许这样做。

每次你有一个解析来执行,因为它比使用Exception更便宜,而且你可以使它成为一个简单的if语句的一部分而不是一个大的try ... catch块。

I'm no c# monkey but... 我不是c#monkey但是......

An exception interrupts normal code flow by transferring processing to the catch block. 异常通过将处理转移到catch块来中断正常的代码流。

TryParse will give you more control (eg highlight an error in a text box) rather then relying on the Exception mechanism. TryParse将为您提供更多控制(例如,在文本框中突出显示错误),而不是依赖于异常机制。

If you're doing validation of input on a form, you could set the ErrorProvider on the control (or a MessageBox or some other notification) when it returns false. 如果您正在对表单上的输入进行验证,则可以在返回false时在控件(或MessageBox或其他通知)上设置ErrorProvider。 It's not an exceptional case because like others have said, you should plan for it. 这不是一个例外情况,因为像其他人所说,你应该为它做好计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM