【问题标题】:Code unreachable when comparing types [closed]比较类型时无法访问代码[关闭]
【发布时间】:2016-02-01 16:21:42
【问题描述】:

问题:我的 else 语句无法访问,我做错了什么?

在编程方面非常新,我正在尝试比较类型,例如当我要求整数时人们无法输入字符串。

我的代码可能很糟糕,如果我能得到一个标题该怎么做以及为什么 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));
    }

}

:c

【问题讨论】:

  • 那里有问题吗?
  • 请避免在您的代码中使用goto's,我认为这是非常糟糕的编码习惯
  • i(true) 错了,这样一行没有意义

标签: c# if-statement types compare unreachable-code


【解决方案1】:

其实不是代码问题,而是逻辑问题……

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 代码块在任何逻辑情况下都不可能执行,因此可以将整个代码块简化为:

Console.WriteLine("Thanks");

为了执行else 块,if 语句中检查的条件需要为false。您目前没有检查任何实际情况,只是一个硬编码的 true 值。

也许您打算使用上一行代码的结果?像这样的:

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

if (typesAreSame)
{
    //...

【讨论】:

  • 是的!那是我一直在寻找的;谢谢大卫!
  • @ArvidWikströmWiren 那么你应该把它标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多