【发布时间】:2022-11-19 06:19:34
【问题描述】:
Code and Debug window 您可以清楚地看到我的字符串变量scoreText 的值为“9”,但是无法转换为整数。
这是整个异常消息,但我看不出这有什么帮助:
FormatException:输入字符串的格式不正确。 System.Number.ThrowOverflowOrFormatException(System.Boolean 溢出,System.String overflowResourceKey)(在 <9aad1b3a47484d63ba2b3985692d80e9>:0) System.Number.ParseInt32 (System.ReadOnlySpan
1[T] value, System.Globalization.NumberStyles styles, System.Globalization.NumberFormatInfo info) (at <9aad1b3a47484d63ba2b3985692d80e9>:0) System.Int32.Parse (System.String s, System.IFormatProvider provider) (at <9aad1b3a47484d63ba2b3985692d80e9>:0) System.Convert.ToInt32 (System.String value) (at <9aad1b3a47484d63ba2b3985692d80e9>:0) ScoreChanger.ChangeScore () (at Assets/ScoreChanger.cs:21) UnityEngine.Events.InvokableCall.Invoke () (at <86acb61e0d2b4b36bc20af11093be9a5>:0) UnityEngine.Events.UnityEvent1[T0].Invoke (T0 arg0) (at <86acb61e0d2b4b36bc20af11093be9a5>:0) TMPro.TMP_InputField.SendOnEndEdit ()(位于 Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:3149) TMPro.TMP_InputField.ReleaseSelection ()(位于 Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:4146) TMPro.TMP_InputField.DeactivateInputField(System.Boolean clearSelection)(位于 Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:4184) TMPro.TMP_InputField.OnDeselect(UnityEngine.EventSystems.BaseEventData 事件数据)(位于 Library/PackageCache/com.unity.textmeshpro@3.0.6/Scripts/Runtime/TMP_InputField.cs:4196) UnityEngine.EventSystems.ExecuteEvents.Execute(UnityEngine.EventSystems.IDeselectHandler 处理程序,UnityEngine.EventSystems.BaseEventData 事件数据)(位于 Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:120) UnityEngine.EventSystems.ExecuteEvents.Execute[T](UnityEngine.GameObject 目标,UnityEngine.EventSystems.BaseEventData 事件数据,UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] 仿函数)(位于 Library/PackageCache/com.unity.ugui@1.0 .0/Runtime/EventSystem/ExecuteEvents.cs:272) UnityEngine.EventSystems.EventSystem:Update()(位于 Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)我正在使用 Convert.ToInt32(string) 来转换它。但是,它最终抛出异常“输入字符串的格式不正确”。我尝试手动将 scoreText 的值更改为“9”并且它有效。这有什么意义?
【问题讨论】:
-
您能否将该字符串传递给
Encoding.UTF8.GetBytes(实际字符串本身,如果您手动键入“9”则不会)并显示结果?这种事情有时是由于字符串中存在不可见字符造成的 -
请重新阅读 minimal reproducible example 指南和 edit 问题,以将代码和必要的数据作为格式正确的文本内嵌在帖子中。
-
@harold 是的,这是结果,但我是初学者,所以我不确定这意味着什么。 imgur.com/a/VLFNVHN
-
尝试在您的字符串上使用 Trim()
-
好吧,我不认为盲目地采用这样的子字符串是一个安全的解决方案。这次成功了,但是当该字符串具有一些不同的值时呢?为什么里面有一个零宽度的空间?为什么
trim不起作用?
标签: c# unity3d parsing type-conversion formatexception