在 c#、Convert vs Parse 中获取输入的正确方法是什么
问题描述:
我在 c# 中看到了一些其他方法来从用户那里获取输入,这真的很令人困惑.我可以同时使用这两种方式来获取输入还是只用于浮动?
I saw some other ways to take input from user in c# and it's really confusing. Can I use both the way to take input or is it only for float?
是否有更多的输入方式?
Is there more ways to take input?
float myAge;
myAge = Convert.Toint64(Console.ReadLine());
对比
float myAge;
float myAge = float.Parse(Console.ReadLine());
答
我推荐 TryParse
,以避免在用户没有提供有效浮点数时出现异常.
I would recommend TryParse
, to avoid exceptions in case user does not provide a valid float.
float myAge;
float.TryParse(Console.ReadLine(), out myAge);
或在 1 行 float.TryParse(Console.ReadLine(), out float myAge);
TryParse
将返回一个布尔值,您可以使用它来检查该值是否为有效浮点数.
TryParse
will return a bool you can use to check if the value is a valid float.
if(float.TryParse(Console.ReadLine(), out myAge)){
//do stuff
}else{
Console.WriteLine("You did not give a float");
}
double
, int
也有这些方法.它不仅适用于 floats
.
double
, int
have these methods too. Its not only for floats
.