c# - 在 c# 中接受输入的正确方法是什么,Convert vs Parse
问题描述
我在 c# 中看到了其他一些从用户那里获取输入的方法,这真的很令人困惑。 我可以同时使用这两种方式来获取输入还是仅用于 float?
有更多的方法来接受输入吗?
float myAge;
myAge = Convert.Toint64(Console.ReadLine());
对比
float myAge;
float myAge = float.Parse(Console.ReadLine());
解决方案
我会建议TryParse
,以避免在用户不提供有效浮点数的情况下出现异常。
float myAge;
float.TryParse(Console.ReadLine(), out myAge);
或在 1 行float.TryParse(Console.ReadLine(), out float myAge);
TryParse
将返回一个布尔值,您可以使用它来检查该值是否为有效浮点数。
if(float.TryParse(Console.ReadLine(), out myAge)){
//do stuff
}else{
Console.WriteLine("You did not give a float");
}
double
,int
也有这些方法。它不仅适用于floats
.
推荐阅读
- javascript - React JS - 承诺在执行完成之前返回。异步功能不起作用
- php - 创建 Facebook 样式通知 (Laravel)
- python - 使用 SQLite 在 Django 中为每个实体对象存储多个图像
- python - 在 laravel 中运行 python 脚本
- python - 这个搜索功能有什么问题?
- python - 需要从 youtube 视频页面获取链接,链接是通过 javascript 加载的。使用 python 请求模块
- excel - 根据上面的非空白单元格填充空白单元格
- python-3.x - 如何使用 selenium python 自动分页?(无需手动选择下一步按钮)
- google-apps-script - 如果未填充单元格,则停止激活脚本
- json - 如何从此 json 字段中获取数据?