繁体   English   中英

C#中可能的意外参考比较

[英]Possible unintended reference comparison in C#

我正在获得可能的意外参考比较; 要获得值比较,请在GetPrice方法的if语句上将左侧的内容强制转换为“ string”。 它在所有“ if(size ==“ Small”)”语句上高亮显示。 这是我的变量:

drinkType = GetDrinkType();
size = GetDrinkSize();
price = GetPrice(size);

private string GetDrinkType()
        {
            string theDrink;
            theDrink = "None Selected";

            if (rdoCoffee.Checked)
            {
                theDrink = "Coffee";
            }
            else if (rdoCoco.Checked)
            {
                theDrink = "Hot Chocolate";
            }
            else if (rdoSmoothie.Checked)
            {
                theDrink = "Smoothie";
            }

            return theDrink;
        }

        private string GetDrinkSize()
        {
            string theSize;
            theSize = "None Selected";

            if (rdoSmall.Checked)
            {
                theSize = "Small";
            }
            else if (rdoMedium.Checked)
            {
                theSize = "Medium";
            }
            else if (rdoLarge.Checked)
            {
                theSize = "Large";
            }
            return theSize;
        }
        private decimal GetPrice(object size)
        {
            decimal thePrice;
            thePrice = 0;
            if (size == "Small")
            {
                thePrice = 1.25m;
            }
            else if (size == "Medium")
            {
                thePrice = 2.50m;
            }
            else if (size == "Large")
            {
                thePrice = 3.35m;
            }
            return thePrice;
        }

size参数声明为object类型,因此编译器不知道它实际上是string类型。 因此,它对类型object使用默认的相等性,这是引用比较。

如果将size的类型更改为string ,它将使用string类中的equals运算符重载,从而执行值比较。

private decimal GetPrice(string size)

发生警告是因为您正在将字符串与对象进行比较。 如果你改变

 if (size == "Small")

 if (size.ToString() == "Small")

警告将被删除。

尝试将GetPrice中的“对象”更改为“字符串”。

由于在GetPrizesize的类型是object ,但是您正在将其与size == "Large"string进行比较。

"string text".Equals(object)更改比较。 "string text".Equals(object) ,如下所示

private decimal GetPrice(object size)
{
      decimal thePrice = 0m;
      if ("Small".Equals(size))
      {
            thePrice = 1.25m;
      }
      else if ("Medium".Equals(size))
      {
            thePrice = 2.50m;
      }
      else if ("Large".Equals(size))
      {
            thePrice = 3.35m;
      }
      return thePrice;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM