C# 比较类型时无法访问代码 问题:我的else语句无法访问,我做错了什么?

C# 比较类型时无法访问代码 问题:我的else语句无法访问,我做错了什么?,c#,if-statement,types,compare,unreachable-code,C#,If Statement,Types,Compare,Unreachable Code,编程非常新,我尝试比较类型,例如,当我要求整数时,人们不能输入字符串 我的代码可能很糟糕,如果我能得到一个标题,告诉我该做什么,为什么if参数跳过了else部分,我会非常高兴的 谢谢 class Program { static void Main(string[] args) { int integer = 0; start: Console.WriteLine("How old are you?: ")

编程非常新,我尝试比较类型,例如,当我要求整数时,人们不能输入字符串

我的代码可能很糟糕,如果我能得到一个标题,告诉我该做什么,为什么if参数跳过了else部分,我会非常高兴的

谢谢

class Program
{
    static void Main(string[] args)
    {            
        int integer = 0;

        start:
        Console.WriteLine("How old are you?: ");
        int svar = int.Parse(Console.ReadLine());

        Utility.CompareTypes(svar, integer);

            if (true)
        {
            Console.WriteLine("Thanks");

        }
            else
            {
                Console.WriteLine("You have to enter a number!");
                goto start;
            }

    }
}

class Utility
{

    public static bool CompareTypes<T01, T02>(T01 type01, T02 type02)
    {
        return typeof(T01).Equals (typeof(T02));
    }

}
类程序
{
静态void Main(字符串[]参数)
{            
整数=0;
开始:
Console.WriteLine(“你多大了?:”);
int svar=int.Parse(Console.ReadLine());
CompareTypes(svar,integer);
如果(真)
{
Console.WriteLine(“谢谢”);
}
其他的
{
WriteLine(“您必须输入一个数字!”);
转到开始;
}
}
}
类效用
{
公共静态bool隔间(T01类型01、T02类型02)
{
返回typeof(T01).等于(typeof(T02));
}
}

:c

这不是真正的代码问题,而是逻辑问题

if (true) // <--- this will ALWAYS be true
{
    Console.WriteLine("Thanks");
}
else // <--- therefore this will NEVER happen
{
    Console.WriteLine("You have to enter a number!");
    goto start;
}
为了执行
else
块,在
if
语句中检查的条件必须是
false
。您当前没有检查任何实际情况,只是硬编码的
true

也许您想使用前一行代码的结果?大概是这样的:

var typesAreSame = Utility.CompareTypes(svar, integer);

if (typesAreSame)
{
    //...

这不是真正的代码问题,而是逻辑问题

if (true) // <--- this will ALWAYS be true
{
    Console.WriteLine("Thanks");
}
else // <--- therefore this will NEVER happen
{
    Console.WriteLine("You have to enter a number!");
    goto start;
}
为了执行
else
块,在
if
语句中检查的条件必须是
false
。您当前没有检查任何实际情况,只是硬编码的
true

也许您想使用前一行代码的结果?大概是这样的:

var typesAreSame = Utility.CompareTypes(svar, integer);

if (typesAreSame)
{
    //...

在某个地方有问题吗?请避免在你的代码中出现
goto的
在我看来非常糟糕的编码实践是错误的,在这样一行中没有意义在某个地方出现问题吗?请避免在你的代码中出现
goto的
在我看来非常糟糕的编码实践是错误的,这样的话毫无意义是的!那是我一直在寻找的;谢谢你,大卫@ArvidWikströmWiren那么你应该把它标记为答案。是的!那是我一直在寻找的;谢谢你,大卫@ArvidWikströmWiren那么你应该把它标记为答案。