[英]c# methods declaring variables
i am making a class in which i have used method .they variables are declared directly in method paramter.why i cant declare int below like string. 我正在使用一个方法使用的类。它们的变量直接在方法paramter中声明。为什么我不能像字符串一样在下面声明int。
class studentinfoget
{
static void Getstudnetinformation(string firstname, string lastname, string birthday, string address, int cellnumber, int homenumber)
{
Console.WriteLine("enter your first name");
firstname = Console.ReadLine();
Console.WriteLine("enter your LAST NAME");
lastname = Console.ReadLine();
Console.WriteLine("enter your brithday ");
birthday = Console.ReadLine();
Console.WriteLine("enter birthday");
address = Console.ReadLine();
Console.WriteLine("enter address");
cellnumber = Console.ReadLine();
Console.WriteLine("enter adress");
}
Error for this code is 该代码的错误是
CS0029 C# Cannot implicitly convert type 'string' to 'int'
CS0029 C#无法将类型'string'隐式转换为'int'
You can use int.TryParse()
to convert the input into an integer. 您可以使用
int.TryParse()
将输入转换为整数。
int.TryParse(Console.ReadLine(), out cellnumber);
However, if the test fails, cellnumber
will be 0. 但是,如果测试失败,则
cellnumber
将为0。
A cell number may not necessarily be an integer though - you could have somebody entering the cell number as "XXX-XXX XXXX"
, or it may have more than 10 digits, in which case you may exceed the int.MaxValue
of 2,147,483,647. 单元格编号不一定是整数-您可以输入
"XXX-XXX XXXX"
作为单元格编号,或者它可以包含10位以上的数字,在这种情况下,您可能会超过int.MaxValue
。 Also, the starting digit might be a 0, which would then be stripped out when stored and render the phone number invalid. 同样,起始数字可能是0,然后在存储时会被剥离并导致电话号码无效。
In this case I would recommend storing the value as a string as at least then the user-entered format will be preserved. 在这种情况下,我建议将值存储为字符串,因为至少会保留用户输入的格式。
cellnumber
is declared as an int
but Console.ReadLine
returns a string
. cellnumber
声明为int
但Console.ReadLine
返回一个string
。 You need to convert the entered text to a number: 您需要将输入的文本转换为数字:
int.TryParse(Console.ReadLine(), out cellnumber);
TryParse
is used to handle invalid input - if the user enters Phone
or something that isn't a number TryParse
won't throw an exception, it will return false
but execution will continue. TryParse
用于处理无效输入-如果用户输入Phone
或非数字的内容, TryParse
不会引发异常,它将返回false
但执行将继续。
you may use cellnumber = Int32.Parse(Console.ReadLine());
您可以使用
cellnumber = Int32.Parse(Console.ReadLine());
but you should change cellnumber and homenumber to string variable. 但是您应该将cellnumber和homenumber更改为字符串变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.