c#運算子多載

來源:互聯網
上載者:User

標籤:

允許使用者定義的類型通過使用 operator 關鍵字定義靜態成員函數來重載運算子。

注意必須用public修飾,必須是類的靜態方法。同時,重載相等運算子(==)時,還必須重載不相等運算(!=)。< 和 > 運算子以及 <= 和 >= 運算子也必須成對重載。

可以重載的運算子:
可以重載的一元運算子:+、-、!、~、++、--、true 和 false
可以重載的二進位運算子:+, -, *, /, %, &, |, ^, <<, >>
可以重載的比較子:==, !=, <, >, <=, >=

不能重載的運算子:
&&, || 條件邏輯運算子不能重載,但可使用能夠重載的 & 和 | 進行計算。
[]不能重載數組索引運算子,但可定義索引器。
()不能重載轉換運算子,但可定義新的轉換運算子(請參見 explicit 和 implicit)。
+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=賦值運算子不能重載,但 += 可使用 + 計算
=、.、?:、->、new、is、sizeof 和 typeof 不能重載這些運算子。

一個簡單的例子:

using System;  
using System.Reflection;  
  
namespace HelloCSharp  
{  
    class OperatorTest  
    {  
        public int Value { get; set; }  
  
        public static void Main()  
        {  
            OperatorTest o1 = new OperatorTest();  
            o1.Value = 11;  
  
            OperatorTest o2 = new OperatorTest();  
            o2.Value = 22;  
  
            OperatorTest o3 = o1 + o2;  
            Console.WriteLine(o3.Value);  
        }  
  
        public static OperatorTest operator + (OperatorTest o1, OperatorTest o2)  
        {  
            OperatorTest o = new OperatorTest();  
            o.Value = o1.Value + o2.Value;  
            return o;  
        }  
    }  
}  

c#運算子多載

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.