因此,编译器不会允许我重载我的类的==和!=运算符。这里是一流的样子:C#修饰符覆盖对此项无效
public class Item
{
public string _name;
public double _weight;
public decimal _wholesalePrice;
public int _quantity;
public Item(string name, double weight, decimal wholesalePrice, int quantity)
{
_name = name;
_weight = weight;
_wholesalePrice = wholesalePrice;
_quantity = quantity;
}
public static override bool operator ==(Item left, Item right)
{
if (left._name == right._name)
{
return true;
}
return false;
}
public static override bool operator !=(Item left,Item right)
{
return !(left == right);
}
}
编译器不断告诉我“的修改‘覆盖’是无效的这个项目起初我还以为我可能没有声明的基础方法,虚拟的,但我类并没有的。任何想法是怎么回事?
幸运的是,我覆盖了下面的这些方法:)我只是没有包含它们。无论如何,等于什么?我什么时候会用这个来代替==运算符? – Nick 2012-07-29 15:15:58
==运算符通常比较对象引用,而不是对象内的值。 Equals方法比==运算符更频繁地用于比较对象的值。大多数.NET类(Dictionary等)都使用Equals方法来比较对象,所以如果你只是重载==操作符,这些类将不会像预期的那样工作。 – 2012-07-29 17:58:11