String must be exactly one character long怎么解决? C#.net 错误

How to solve String must be exactly one character long? C# .net error

我正在尝试使用 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);

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

您可以这样做:始终强烈建议像这样捕获 FormatException 和 ArgumentNullException link:

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();

为什么将 "Default" 作为默认回复?您要么留空,要么在此处输入“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