オペレータ、オペレータ、手段としても知られている(オペレータ)、 、、演算子オーバーロードであり、C#は、ユーザ定義型は、種々の演算子の意味を再定義することができ、同様に、(オペレータはオーバーロード)。たとえば、2つの日付と時刻を減算する(DateTime)は、2つの日付間の時間間隔(TimeSpan)を表します。日付と時刻に時間間隔を追加すると、別の日付と時刻が得られます。+
-
*
DateTime now = DateTime.Now;
DateTime start = new DateTime(2000, 1, 1);
TimeSpan c = now - start;
Console.WriteLine(c.TotalDays);
実際、ここでの時間減算の演算子(マイナス記号)は「op_Subtraction
」と呼ばれる特別なメソッドです.NET framework
。APIドキュメントでは、この演算子は(演算子)で呼び出さDateTime
れます。Operators
op_Subtraction
例:複素数を計算するためのカスタム演算子のオーバーロード。
using System;
public struct Complex
{
public double real;
public double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 单元运算
public static Complex operator +(Complex c1) {
return c1; }
public static Complex operator -(Complex c1) {
return new Complex(-c1.real, -c1.imaginary); }
public static bool operator true(Complex c1) {
return c1.real != 0 || c1.imaginary != 0; }
public static bool operator false(Complex c1) {
return c1.real == 0 && c1.imaginary == 0; }
// 双元运算
public static Complex operator +(Complex c1, Complex c2) {
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary); }
public static Complex operator -(Complex c1, Complex c2) {
return c1 + (-c2); }
public static Complex operator *(Complex c1, Complex c2) {
return new Complex(c1.real * c2.real - c1.imaginary * c2.imaginary,
c1.real * c2.imaginary + c1.imaginary * c2.real);
}
public static Complex operator *(Complex c, double k) {
return new Complex(c.real * k, c.imaginary * k); }
public static Complex operator *(double k, Complex c) {
return c * k; }
public override string ToString() {
return (System.String.Format("({0} + {1}i)", real, imaginary));
}
}
static void Main(string[] args) {
Console.WriteLine("Hello World!");
Complex num1 = new Complex(2, 3);
Complex num2 = new Complex(3, 4);
Complex result = num1 ? -num1 * 5 + num1 * num2 : new Complex(0, 0);
Console.WriteLine("First complex number: {0}", num1);
Console.WriteLine("Second complex number: {0}", num2);
Console.WriteLine("The result is: {0}", result);
}
演算結果: