如何解决String必须正好一个字符长? C#.net错误

时间:2018-11-08 02:56:08

标签: c# .net string char inputbox

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

任何想法如何解决这个问题?预先感谢。

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作:始终强烈建议您通过以下链接捕获FormatException和ArgumentNullException:

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

let button = document.querySelector('#button');
let quote = document.querySelector('#quote');

function getInfoFetch(){
  fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
    .then(response => response.json())
    .then((data) => {
      console.log(data); 
      //this is an array with object(index = 0) inside [{...}]
      quote.innerText = data[0].quote;
    })
    .catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch);

或者您可以使用:

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
}

答案 1 :(得分:0)

为什么将“默认”作为默认响应?您可以将其保留为空白,或在其中添加“ 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