2024年5月3日发(作者:)

学习笔记

se

2011-1-25

When parsing integers in the programming language, you want to avoid

exceptions and handle errors gracefully. To accomplish this, you can use the

se shared method, which provides a tester-doer pattern to parsing.

Here, we describe and demonstrate the se method in the

language.

程序员之家 C#学习笔记

目录

Using se ...................................... 1

Summary ..................................................... 2

1

程序员之家 C#学习笔记

When parsing integers in the programming language, you want

to avoid exceptions and handle errors gracefully. To accomplish this,

you can use the se shared method, which provides a

tester-doer pattern to parsing. Here, we describe and demonstrate the

se method in the language.

Using se

This example demonstrates the se function, which is very

useful when you are not certain the input String is valid. It will

not throw an exception if the input string is invalid. Instead, it

will return false. The example further shows how you can test the return

value of TryParse.

=== Program that uses TryParse () ===

Module Module1

Sub Main()

' An invalid number string

Dim s As String = "x"

' Try to parse it. If it isn't a number, use -1

Dim num As Integer

If Not se

(s, num) Then

num = -1

End If

' Writes -1 to the screen

ine(num)

End Sub

End Module

=== Output of the program ===

-1

Explanation of the above example. The Main entry point is defined above,

and the first String is not a valid integer. When we send it to

se, the function returns False. The If Not statement

then assigns the number to -1. The effect is that the Integer is either

set to the number in the String, or -1 if there is no valid number

in the String.

1

程序员之家 C#学习笔记

Summary

Although parsing integers in the language may seem less

intuitive with the se method, this approach typically

simplifies your code. Not only that, but it leads to more robust and

crash-proof code, furthering your goal of stability and relative

invulnerability.

2