首页 > 解决方案 > 在 c# 中接受输入的正确方法是什么,Convert vs Parse

问题描述

我在 c# 中看到了其他一些从用户那里获取输入的方法,这真的很令人困惑。 我可以同时使用这两种方式来获取输入还是仅用于 float

有更多的方法来接受输入吗?

float myAge;

myAge = Convert.Toint64(Console.ReadLine());

对比

float myAge;

float myAge = float.Parse(Console.ReadLine());

标签: c#variables

解决方案


我会建议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");
}

doubleint也有这些方法。它不仅适用于floats.


推荐阅读