Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将类型字符串转换为int_C# - Fatal编程技术网

C# 如何将类型字符串转换为int

C# 如何将类型字符串转换为int,c#,C#,我已经创建了一些类,在一个例子中,我希望程序读取答案(数字)。我尝试将类设置为string和int,但仍然存在问题。请容忍我,我才刚开始学习编程 public **int** Age { get; set; } Animal cuddle = new Animal(); cuddle.Color = ""; cuddle.Age = 0; cuddle.Name = ""; cuddle.Type =

我已经创建了一些类,在一个例子中,我希望程序读取答案(数字)。我尝试将类设置为string和int,但仍然存在问题。请容忍我,我才刚开始学习编程

public **int** Age { get; set; }
Animal cuddle = new Animal();
            cuddle.Color = "";
            cuddle.Age = 0;
            cuddle.Name = "";
            cuddle.Type = "";
Console.WriteLine("Hi, {0} How old do you want your {1,2} to be?\n Remember, if your {3} is older then 5 you will have to give her double!!!", name, cuddle.Color, player);
            cuddle.Age = **Console.ReadLine**();
            if (cuddle.Age < 5)
            {
那它就不接受了

if (**cuddle.Age < 5**)
if(**cuddle.Age<5**)

我尝试过不使用括号和/或使用
(**cuddle.Age=<5**)

您可以根据用户输入转换为int:

int theInt = Convert.ToInt32(Console.ReadLine());
这可能是这个问题的重复:

int age=0;
if(int.TryParse(Console.ReadLine(),out age))//可以将其解析为整数:
{
if(年龄<5岁)
{
//做你的工作
}
}
当输入无法解析时,您可以更进一步,重复读取行:

int age = 0;
while(!int.TryParse(Console.ReadLine(), out age));
if(age < 5)
{
   // do your work
}
int-age=0;
而(!int.TryParse(Console.ReadLine(),out age));
if(年龄<5岁)
{
//做你的工作
}

这是感谢阿什坎的

。它没有显示任何错误,但最后没有工作。当这个问题被回答时,我被拒之门外。你能帮我吗?@Itzik请进来讨论
int age = 0;
if(int.TryParse(Console.ReadLine(), out age)) //It can be parsed as integer:
{
     if(age < 5)
     {
        // do your work
     }
}
int age = 0;
while(!int.TryParse(Console.ReadLine(), out age));
if(age < 5)
{
   // do your work
}