UInt16。用例子解析 C# 中的(字符串)方法
原文:https://www . geesforgeks . org/uint 16-parse string-method-in-c-sharp-with-examples/
UInt16。解析(字符串)方法用于将数字的字符串表示转换为其等效的 16 位无符号整数。
语法:
public static ushort Parse (string str);
这里,字符串是包含要转换的数字的字符串。字符串的格式为【可选空格】【可选符号】数字【可选空格】。这个符号可以是正的,也可以是负的。但是负号只能和零一起使用,否则会抛出overowexception。
返回值:是一个 16 位无符号整数,相当于字符串中包含的数字。
异常:
- 参数空异常:如果字符串为空。
- 格式异常:如果字符串格式不正确。
- overoverowexception:如果 str 代表小于T5】MinValueT7】或大于T9】MaxValueT11】的数字。**
以下程序说明了上述方法的使用:
例 1:
// C# program to demonstrate
// UInt16.Parse(String) Method
using System;
class GFG {
// Main Method
public static void Main()
{
// passing different values
// to the method to check
checkParse("65535");
checkParse("15,784");
checkParse("-4589");
checkParse(" 785");
}
// Defining checkParse method
public static void checkParse(string input)
{
try {
// declaring UInt16 variable
ushort val;
// getting parsed value
val = UInt16.Parse(input);
Console.WriteLine("'{0}' parsed as {1}", input, val);
}
catch (OverflowException) {
Console.WriteLine("Can't Parsed '{0}'", input);
}
catch (FormatException) {
Console.WriteLine("Can't Parsed '{0}'", input);
}
}
}
Output:
'65535' parsed as 65535
Can't Parsed '15,784'
Can't Parsed '-4589'
' 785' parsed as 785
示例 2: 适用于参数异常
// C# program to demonstrate
// UInt16.Parse(String) Method
// for ArgumentNullException
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// passing null value as a input
checkParse(null);
}
catch (ArgumentNullException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
catch (FormatException e) {
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
// Defining checkparse method
public static void checkParse(string input)
{
// declaring UInt16 variable
ushort val;
// getting parsed value
val = UInt16.Parse(input);
Console.WriteLine("'{0}' parsed as {1}", input, val);
}
}
Output:
Exception Thrown: System.ArgumentNullException
参考:
版权属于:月萌API www.moonapi.com,转载请注明出处