簡體   English   中英

字符串無法解析為 UInt32

[英]String can't be parsed into UInt32

我正在為 Unity 中的用戶編寫登錄程序。 我有 2 個用於用戶名和密碼的“Text Mesh Pro UGUI”輸入字段。

我需要將用戶名(這是一個數字)轉換為 UInt32 來處理用戶的登錄。

但是這個簡單的字符串 → UInt32 解析存在問題。

這是代碼:

// Note: I have tried typing different Numbers into the input field but in this case, 
// I have tried the same as the test_string (123456)

// This works perfect
string test_string = "123456";

UInt32 test_UInt32 = 0;

if (UInt32.TryParse(test_string, out test_UInt32))
{
    test_UInt32 = UInt32.Parse(test_string);
}

// This never works
UInt32 username_UInt32 = 0;

if (UInt32.TryParse(username.text, out username_UInt32))
{
    username_UInt32 = UInt32.Parse(username.text);
}

// Debugging for me to find the error
Debug.Log(username.text); // Output: 123456
Debug.Log(test_string);   // Output: 123456

Debug.Log(username.text.GetType().ToString());   // Output: System.String
Debug.Log(test_string.GetType().ToString());     // Output: System.String

Debug.Log(username.text.Length.ToString());      // Output: 7
Debug.Log(test_string.Length.ToString());        // Output: 6

// For Testing only => FormatException: Input string was not in a correct format.
username_UInt32 = UInt32.Parse(username.text);

看你的長度不一樣。 你錯過了一些你需要調試的東西

  Debug.Log(username.text.Length.ToString());      // Output: 7
  Debug.Log(test_string.Length.ToString());        // Output: 6

UInt32.Parse Method only 將數字的字符串表示形式轉換為其等效的 32 位無符號整數。 必須有一個特殊字符。 空格可以出現在開頭和結尾,但不能出現在兩者之間。

非常感謝所有這些輸入,它現在按預期工作!

你是對的,有一個隱藏的角色。

這解決了這個問題:

string clean_string = username.text.Replace("\u200B", "")

使用這個清理過的字符串,解析工作得很好。

你救了我的一天。 祝你一切順利!

username.text可能有空格字符,您可以使用此代碼刪除該空格

username.text = username.text.Trim();

然后解析它。

當您使用 TryParse 方法時,無需再次使用 Parse。 只需將代碼更改為此

if (!UInt32.TryParse(username.text, out username_UInt32))
{
    //handle error
}

您沒有意識到.TryParse()不僅會告訴您解析是否成功,還會用新數字填充 out 參數。 您不斷嘗試為該參數分配一個值。

    private void button2_Click(object sender, EventArgs e)
    {
        string test_string = textBox1.Text.Trim();
        if (!uint.TryParse(test_string, out uint test_UInt32))
        {
            MessageBox.Show("Invalid Input");
            return;
        }
        if (!UInt32.TryParse(textBox1.Text.Trim(), out uint username_UInt32))
        {
            MessageBox.Show("Invalid Input");
            return;
        }
        Debug.Print($"The input string is {test_string}, the resulting number is {test_UInt32}, of type {test_UInt32.GetType()}");
        //Output  The input string is 1234, the resulting number is 1234, of type System.UInt32
        Debug.Print($"The input string is {textBox1.Text}, the resulting number is {username_UInt32}, of type {username_UInt32.GetType()}");
        //Output  The input string is 1234, the resulting number is 1234, of type System.UInt32
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM