Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด int.TryParse ใน C#

แปลงการแสดงผลสตริงของตัวเลขเป็นจำนวนเต็ม โดยใช้เมธอด int.TryParse ใน C# หากสตริงไม่สามารถแปลงได้ เมธอด int.TryParse จะคืนค่า false คือค่าบูลีน

สมมติว่าคุณมีการแสดงผลสตริงของตัวเลข:

string myStr = "12";

ตอนนี้เพื่อแปลงเป็นจำนวนเต็ม ให้ใช้ int.TryParse() จะแปลงได้และคืนค่า True:

int.TryParse(myStr, out a);

ตัวอย่าง

using System.IO;
using System;

class Program
{
    static void Main()
    {
        bool res;
        int a;
        string myStr = "12";
        res = int.TryParse(myStr, out a);
        Console.WriteLine("String is a numeric representation: " + res);
    }
}

ผลลัพธ์

String is a numeric representation: True