【问题标题】:c# how do you compare two values in c# if statementc#如何比较c# if语句中的两个值
【发布时间】:2017-10-01 08:57:32
【问题描述】:

我创建了一个简单的矩形类,我需要比较同一个矩形的两侧,但我不知道这怎么可能。在this.width下面的方法isSquare()中出现错误

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rectangle
{
    class Rectangleclass
    {
        private String name; 
        private double length = 0.0;
        private double width = 0.0;

        public Rectangleclass(String n, double l, double w)
        {
            name = n;
            length = l;
            width = w;
        }

        public String Name() { return name; }
        public double Length() { return length; }
        public double Width() { return width; }


        public double Area()
        {
            return length * width;
        }


        public bool IsSquare()
        { 
            if (this.Width() = this.Length())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

    }
}

【问题讨论】:

  • if (this.Width() == this.Length()),总是使用双等号来表示相等。你也可以像这样缩短你的代码:return this.Width() == this.Length();
  • = 是赋值,== 是比较,比较值时必须使用双等号。
  • 这里很容易知道错误是什么,但是以后,不要让我们自己假设或尝试弄清楚。如果您遇到错误,请尽可能明确。
  • 有时阅读错误信息很有用
  • 这个问题不应该发布。您的调试器应该准确地告诉您错误是什么。

标签: c# boolean


【解决方案1】:

您将一个值分配给另一个值,您需要 == 进行比较。

试试这个

    public bool IsSquare()
    { 
        return Width() == Length();
    }

【讨论】:

    【解决方案2】:

    您有语法错误 - 您使用的是赋值运算符 = 而不是比较运算符 ==

    你也可以简化你的逻辑,假设你返回一个布尔值:

        public bool IsSquare()
        { 
            return this.Width() == this.Length();
        }
    

    【讨论】:

      【解决方案3】:

      首先,单个= 表示您正在尝试为某物分配一个值,您没有在那里进行比较,因此 if 语句中的错误。

      此外,您可以将整个方法缩短为一行:

      public bool IsSquare()
      { 
          return this.Width() == this.Length();
      }
      

      【讨论】:

        猜你喜欢
        • 2017-11-16
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-15
        相关资源
        最近更新 更多