C# study notes operator overloading

Operator (operator), also known as operator, means +, -, *and the like, C # allows user-defined types to redefine the meaning of the various operators, which is operator overloading (operator overloading).
For example, subtracting two dates and times (DateTime) represents the time interval between two dates (TimeSpan); while adding a time interval to a date and time, you get another date and time:

	DateTime now = DateTime.Now;
	DateTime start = new DateTime(2000, 1, 1);
	TimeSpan c = now - start;
	Console.WriteLine(c.TotalDays);

In fact, the operator for time subtraction (ie, the minus sign) here is a op_Subtractionspecial method called " ". In .NET frameworkthe API documentation, this operator is called DateTimein Operators(operator) op_Subtraction.

Example: Custom operator overloading to calculate complex numbers.

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);
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114156151