C# operator關鍵字

perator
operator 關鍵字用於在類或結構聲明中聲明運算符。運算符聲明可以採用下列四種形式之一:

public static result-type operator unary-operator ( op-type operand )
public static result-type operator binary-operator ( op-type operand, op-type2 operand2 )
public static implicit operator conv-type-out ( conv-type-in operand )
public static explicit operator conv-type-out ( conv-type-in operand )
參數:

result-type 運算符的結果類型。
unary-operator 下列運算符之一:+ - ! ~ ++ — true false
op-type 第一個(或唯一一個)參數的類型。
operand 第一個(或唯一一個)參數的名稱。
binary-operator 其中一個:+ - * / % & | ^<< >> == != > < >=< =
op-type2 第二個參數的類型。
operand2 第二個參數的名稱。
conv-type-out 類型轉換運算符的目標類型。
conv-type-in 類型轉換運算符的輸入類型。
注意:

前兩種形式聲明瞭用戶定義的重載內置運算符的運算符。並非所有內置運算符都可以被重載(請參見可重載的運算符)。op-type 和op-type2中至少有一個必須是封閉類型(即運算符所屬的類型,或理解爲自定義的類型)。例如,這將防止重定義整數加法運算符。
後兩種形式聲明瞭轉換運算符。conv-type-in 和 conv-type-out中正好有一個必須是封閉類型(即,轉換運算符只能從它的封閉類型轉換爲其他某個類型,或從其他某個類型轉換爲它的封閉類型)。
運算符只能採用值參數,不能採用 ref 或 out 參數。
C#要求成對重載比較運算符。如果重載了==,則也必須重載!=,否則產生編譯錯誤。同時,比較運算符必須返回bool類型的值,這是與其他算術運算符的根本區別。
C# 不允許重載=運算符,但如果重載例如+運算符,編譯器會自動使用+運算符的重載來執行+=運算符的操作。
運算符重載的其實就是函數重載。首先通過指定的運算表達式調用對應的運算符函數,然後再將運算對象轉化爲運算符函數的實參,接着根據實參的類型來確定需要調用的函數的重載,這個過程是由編譯器完成。
任何運算符聲明的前面都可以有一個可選的屬性(C# 編程指南)列表。

using System;
using System.Collections.Generic;
using System.Text;

namespace OperatorOverLoading
{
class Program
{
static void Main(string[] args)
{
Student s1 = new Student(20, "Tom");
Student s2 = new Student(18, "Jack");
Student s3 = s1 + s2;

s3.sayPlus();
(s1 - s2).sayMinus();
Console.ReadKey();
}
}
public class Student
{
public Student() { }
public Student(int age, string name)
{
this.name = name;
this.age = age;

}
private string name;
private int age;

public void sayPlus()
{
System.Console.WriteLine("{0} 年齡之和爲:{1}", this.name, this.age);

}
public void sayMinus() {
System.Console.WriteLine("{0} 年齡之差爲:{1}", this.name, this.age);
}
//覆蓋“+”操作符
public static Student operator +(Student s1, Student s2)
{
return new Student(s1.age + s2.age, s1.name + " And " + s2.name);

}
//覆蓋“-”操作符
public static Student operator -(Student s1, Student s2) {
return new Student(Math.Abs(s1.age - s2.age), s1.name + "And" + s2.name);
}

}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章