不会工作 [英] Int wont work

查看:97
本文介绍了不会工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表框.当我单击数字时,我想在控制台中显示它.有什么原因为什么行不通呢?

Console.WriteLine(Int32.Parse(listBox1.SelectedItems.ToString()));

感谢您的帮助.

I have a listbox of numbers. When I click on the number I want to show it in the console. Is there any reason why this wouldn''t work.

Console.WriteLine(Int32.Parse(listBox1.SelectedItems.ToString()));

Any help is appreciated.

推荐答案

1)如果需要显示数字,则无需解析为int,因为Console.WriteLine()将再次解析为字符串.

2)SelectedItems-您转换的不是用户选择的而是一个或多个数字.这不能在单个parse语句中完成.您需要一个一个地转换所有选定的数字.
1) If you need to display the number, then you dont need to parse to int as Console.WriteLine() will again parse to string.

2) SelectedItems - you are converting not one but one or more number selected by the user. This cannot be done in a single parse statement. You need to convert all selected numbers one by one.


为什么要尝试将字符串转换为int以便将其重新转换为字符串以将其写入控制台?

您可能还会注意到此处 [
Why are you trying to convert a string to an int just so you can reconvert it to a string to write it on the console?

You may also note here[^] that SelectedItems returns a collection and not a single string.


Abhinav是正确的...这就是为什么我将他的答案标记为5,但我想详细说明他的话并提供(希望)对将来有用的提示.

当您遇到这样的错误时,最好的办法是在调试器中逐步执行代码.如果您使用的是Visual Studio,请使用监视"窗口.如果某些操作无法按预期方式工作,请将每个变量放入监视窗口并查看结果.

就您而言,如果您执行了此操作,则可以先将listBox1.SelectedItems.ToString()放在监视窗口中.如果这样做,您将看到它等于:

Abhinav is right...which is why I marked his answer as a 5, but I wanted to elaborate a bit more on what he said and provide (hopefully) some helpful tips for the future.

When you get an error like this, the best thing to do is go through your code step by step in the debugger. If you are using Visual Studio, use your Watch window. If something doesn''t work the way you expected, put each of the variables into the watch window and see the results.

In your case, if you had done this, you could have started by putting listBox1.SelectedItems.ToString() in the watch window. If you had done that, you would have seen that it equaled something like:

System.Windows.Forms.ListBox+SelectedObjectCollection



那可能不是您所期望的.然后,当您使用Parse函数时,它会引发错误,因为它不是数字值.

我的另一建议是,如果您确信它会起作用,请仅使用Parse方法.否则,请改用TryParse.



That''s probably not what you were expecting. Then, when you used the Parse function, it would have thrown an error because it is not a numeric value.

My other suggestion is only use the Parse methods if you are assured that it will work. Otherwise, use TryParse instead.


这篇关于不会工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆