簡體   English   中英

在C#中定義新的算術運算

[英]Define New Arithmetic Operation in 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#類定義自定義算術運算?

當然你可以使用運算符重載

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

運算符重載可以像這樣完成:

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

我想你可以自己找出其他的運營商。 有關更多信息,請參閱本教程: 鏈接到教程

注意:操作符必須放在類本身內(在本例中為Zoo類)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM