【问题标题】:How to solve String must be exactly one character long? C# .net error如何解决字符串必须恰好是一个字符长? C# .net 错误
【发布时间】:2018-11-08 02:56:07
【问题描述】:

我正在尝试使用Microsoft.VisualBasic.dll 从用户那里获取输入。然后将输入从 [string] 转换为 [char] 类型。但是当我运行代码时它给了我这个错误:

*An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
String must be exactly one character long.*

示例代码:

      string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);

      char direction = System.Convert.ToChar(directions);

知道如何解决这个问题吗?提前致谢。

【问题讨论】:

  • 当然,我知道这个“字符串必须恰好是一个字符长”是什么意思。对于directions,我没有设置长度。但是,经过几次尝试,我发现任何超过 1 个值的输入都会出现此错误。相反,只有输入 1 个值(字母数字)才能正常工作。
  • 记住一个字符是单个字符,而字符串是0个或多个字符串在一起。
  • 你没有设置长度,当然。但是你设置了一个 specific 长度的值,不是吗?我认为 1 次尝试足以确定字符串“12”的长度为 2。

标签: c# .net string char inputbox


【解决方案1】:

您可以这样做:始终强烈建议像此链接一样捕获 FormatException 和 ArgumentNullException:

https://docs.microsoft.com/en-us/dotnet/api/system.convert.tochar?view=netframework-4.7.2#System_Convert_ToChar_System_String_

char direction;

string directions = Microsoft.VisualBasic.Interaction.InputBox("1 = Buy, 2 = Sell", "Select side", "Default", 700, 400);

if(!string.IsNullOrEmpty(directions) && directions.Trim().Length == 1)
  direction = System.Convert.ToChar(directions);
else {
  direction = directions.FirstOrDefault(); // if thats what your logic
}

或者你可以使用:

char direction = directions.FirstOrDefault();

【讨论】:

  • 它有效,谢谢!但是为什么我不能使用System.Convert.ToChar(); 来转换呢?
  • 是您的字符串长度 1 或者您在输入中放置空格或按回车键..等等..很多原因..
  • 您可能还想像这样检查 null:directions?.FirstOrDefault()
【解决方案2】:

您为什么将“默认”作为默认响应?您要么将其留空,要么将“1”或“2”放在那里。

在转换为方向之前还要检查用户的答案:

If directions <> "1" And directions <> "2" Then
    'display error message to user
Else
    char direction = System.Convert.ToChar(directions);
    'proceed with your business logic
End If

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2020-04-07
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-11-20
    相关资源
    最近更新 更多