简体   繁体   中英

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. And to me, that's basically the same thing as using a try/catch block with the catch returning an error message.

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. 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; use TryParse if you don't. 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.

在可能的情况下,使用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和if是一种很好的方法。

Well int.TryParse returns a bool allowing you to test if it was successful instead of catching an exception. 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...

An exception interrupts normal code flow by transferring processing to the catch block.

TryParse will give you more control (eg highlight an error in a text box) rather then relying on the Exception mechanism.

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. It's not an exceptional case because like others have said, you should plan for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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