如何解决字符串长度必须正好为一个字符的问题?C#.net错误

如何解决字符串长度必须正好为一个字符的问题?C#.net错误,c#,.net,string,char,inputbox,C#,.net,String,Char,Inputbox,我正在尝试使用Microsoft.VisualBasic.dll从用户处获取输入。然后将输入从[字符串]转换为[字符]类型。但是当我运行代码时,它给了我这个错误: *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

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

*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,如下链接:

或者您可以使用:

char direction = directions.FirstOrDefault();
为什么把“默认”作为默认响应?你要么把它留空,要么把“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
如果方向“1”和方向“2”,则
'向用户显示错误消息
其他的
字符方向=System.Convert.ToChar(方向);
“继续你的业务逻辑
如果结束

当然,我知道“字符串必须正好有一个字符长”的意思。对于
方向
,我没有设置长度。但是,经过几次尝试,我发现任何超过1个值的输入都会得到这个错误。相反,只有1个值(字母数字)的输入才能正常工作。请记住,字符是单个字符,而字符串是0个或多个串在一起的字符。确实,您没有设置长度。但是你设定了一个特定长度的值,不是吗?我认为,尝试一次就足以确定字符串“12”的长度为2。它可以工作,谢谢!但是为什么我不能使用
System.Convert.ToChar()在我的情况下要转换吗?字符串长度是1还是在输入中输入空格或按enter键。。等等。原因很多。您可能还需要像这样检查null:
directions?.FirstOrDefault()
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