在C#中定义新的算术运算

时间:2015-10-08 12:43:32

标签: c#

我们说我创建了一个简单的课程。

class Zoo {
  public int lionCount;
  public int cheetahCount;
  Zoo(lions, cheetahs) { 
    lionCount = lions;
    cheetahCount = cheetahs;
  }
}

现在让我说我有2个动物园。

Zoo zoo1 = new Zoo(1,2);
Zoo zoo2 = new Zoo(3,5);

是否可以为此类定义算术运算,例如......

Zoo zoo3 = zoo1 + zoo2; //makes a zoo with 4 lions and 7 cheetahs
Zoo zoo4 = zoo1 * zoo2; // makes a zoo with 3 lions and 10 cheetahs

换句话说,如何为C#类定义自定义算术运算?

2 个答案:

答案 0 :(得分:7)

当然可以使用运算符重载

class Zoo 
{
  public int lionCount;
  public int cheetahCount;

  Zoo(int lions, int cheetahs) 
  { 
    lionCount = lions;
    cheetahCount = cheetahs;
  }

  public static Zoo operator +(Zoo z1, Zoo z2) 
  {
    return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
  }
}

其他运算符的处理方式几乎相同; - )

有关它的更多信息,请检查https://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

答案 1 :(得分:3)

运算符重载可以这样完成:

   public static Zoo operator +(Zoo z1, Zoo z2) 
   {
      return new Zoo(z1.lionCount + z2.lionCount, z1.cheetahCount + z2.cheetahCount);
   }

我认为你可以自己找出其他的运营商。有关详细信息,请参阅本教程:link to tutorial

注意:运算符必须放在类本身(本例中为Zoo类)