avi*_*irk -1 c# exception winforms
我试图通过Windows窗体反转一个字符串,但由于任何原因for循环在我执行代码时给出异常.
System.NullReferenceException:对象引用未设置为对象的实例
Button_Click事件
string input=textBox1.Text;
input=Convert.ToString(Console.ReadLine());
string output="";
if(textBox1.Text=="")
{
MessageBox.Show("Sorry! You have not given any input for perform action");
}
else
{
try{
for(int i=input.Length-1; i>=0; i--)
{
output= output+input[i];
}
textBox2.Text=output;
}
catch(Exception ex)
{
MessageBox.Show(""+ex);
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然相同的逻辑与控制台应用程序完美配合.我知道我缺少非常基本的东西但是目前我没有想法.
Mar*_*ell 13
在winform中,Console.ReadLine()返回null(因为没有控制台).同样,Convert.ToString((string)null)回报null.你不能打电话给.Length(在for)null.关键代码:
input=Convert.ToString(Console.ReadLine());
...
for(int i=input.Length-1; i>=0; i--)
Run Code Online (Sandbox Code Playgroud)
此外,作为一个小问题:通过串联构建字符串是非常低效的.
| 归档时间: |
|
| 查看次数: |
112 次 |
| 最近记录: |