在C#中, Char.TryParse()是Char类方法,用于将值从给定的字符串转换为其等效的Unicode字符。其性能优于Char.Parse()方法。
句法 :
public static bool TryParse(string str, out char result)
范围:
- str: It is System.String type parameter which can contain single character or NULL.
- result: This is an uninitialized parameter which is used to store the Unicode character equivalent when the conversion succeeded, or an undefined value if the conversion failed. The type of this parameter is System.Char.
返回类型:如果成功转换了字符串,则方法返回True ,否则返回False。因此,此方法的类型为System.Boolean 。
注意:当字符串为NULL或长度等于1时,转换将失败。示例1:下面是一个演示Char.TryParse()方法用法的程序。
// C# program to illustrate the
// Char.TryParse () Method
using System;
class GFG {
// Main Method
static public void Main()
{
// Declaration of data type
bool result;
Char value;
// Input Capital letter A
result = Char.TryParse("A", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
// Input Capital letter Z
result = Char.TryParse("Z", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
// Input Symbol letter
result = Char.TryParse("$", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
// Input number
result = Char.TryParse("100", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
// Input small letter z
result = Char.TryParse("z", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
}
}
输出:
True
A
True
Z
True
$
False
True
z
示例2:下面的程序演示了Char.TryParse()方法的使用,其中输入不是单个字符,而是以符号开头。
// C# program to illustrate the
// Char.TryParse () Method
using System;
class GFG {
// Main Method
static public void Main()
{
// Declaration of data type
bool result;
Char value;
// Input is String return false
result = Char.TryParse("GeeksforGeeks", out value);
// Display boolean type result
Console.WriteLine(result);
Console.WriteLine(value.ToString());
// Input letter start with symbol <
result = Char.TryParse("
输出:
False
False