首页 > 解决方案 > 我正在使用一系列 if/else 语句,但不是让我在运行时“通过”它们,而是直接进入最后一个 else 语句

问题描述

(初学者在这里使用 c# 在 Visual Studio 上测试 if/else 语句)我在 Visual Studio 中打开了两个窗口,其中一个我创建了我需要的类:

{
       public string firstName { get; set; }
       public string lastName { get; set; }

        public string fullName
        {
            get
            {
                return firstName + lastName;
            }
        }


    }

和我所有的 if/else 语句:

{
            Person person = new Person();
            person.firstName = "John";
            person.lastName = "Doe";
            if (person.fullName == "John Doe")
            {
                Console.WriteLine("Welp... you've passed... you want another test?");
                string x = Console.ReadLine();
                if (x == "Yes")
                {
                    Console.WriteLine("Alright... what's 1+1?");
                    string y = Console.ReadLine();
                    if (y == "2")
                    {
                        Console.WriteLine("Yay! You're right!");
                    }
                    else
                    {
                        Console.WriteLine("oop... that's wrong my dude");
                    }

                }
                 else 
                {
                    Console.WriteLine("Lame... guess  that's bye for now.");
                }

            }
            else
            {
                Console.WriteLine("oop... ya didn't pass. guess that's bye for now.");
            }

        }

当我运行它时,它没有让我遍历所有 if/else 语句,而是直接将我带到最后一个 else 语句,并打印oop... ya didn't pass. guess that's bye for now.出对不起长度和任何令人困惑的东西(我仍在研究我的词汇量哈哈) 感谢您抽出时间为初学者。

标签: c#visual-studio-2019

解决方案


fullNameJohnDoe名称中不包含空格,因此结果是John Doe.

简单地改变:

 public string fullName
        {
            get
            {
                return firstName + lastName;
            }
        }

 public string fullName
        {
            get
            {
                return firstName + " " + lastName;
            }
        }

这样做之后,这个守卫将评估为true

if (person.fullName == "John Doe")

推荐阅读