类型的操作符重载

本文关键字:重载 操作符 类型 | 更新日期: 2023-09-27 18:01:29

当我输入问题时,我可以看到操作符重载列表…问题排成一行。它们中的大多数要么用于c++,要么用于Haskell。我的问题是针对c#的,有人可能会说逻辑是一样的。我的问题是我想了解c#上下文中的操作符重载。

我正在看一个教程,它显示,

DateTime dt1 = new DateTime();
//do some work
DateTime dt2 = new DateTime();
TimeSpan ts = dt2 - dt1;

,作者说,利用-在DateTime数据类型是最好的操作符重载的例子。我所能看到的是一个日期被另一个日期减去,并保存到TimeSpan对象中。没有使用operator关键字,也没有使用static关键字。

我觉得很难理解。有人能解释一下这是怎么回事吗?这是否意味着在上面的ts = dt2 - dt1下面,发生了public static DateTime operator -(DateTime, DateTime) ?更新:

第二个例子:

//some parameterized constructor is here to set X, Y
public static Point operator +(Point p1, Point p2)
{   
    Point p = New Point();
    p.X = p1.X + p2.X;
    p.Y = p2.Y + p2.Y;
    return p
{

在这种情况下,操作数必须与返回类型相同。

类型的操作符重载

operator关键字在声明重载操作符时使用,而不是在使用重载操作符时使用。

所以操作符应该写成这样:

public static TimeSpan operator -(DateTime lhs, DateTime rhs)
{
    // Code to execute
}

使用操作符时,这些都不会受到干扰-您只需在已经展示的那种代码中使用它。所以这一行:

TimeSpan ts = dt2 - dt1;

将调用上面给出的代码。

示例代码:

using System;
public class Int32Wrapper
{
    private readonly int value;
    public int Value { get { return value; } }
    public Int32Wrapper(int value)
    {
        this.value = value;
    }
    public static Int32Wrapper operator +(Int32Wrapper lhs, Int32Wrapper rhs)
    {
        Console.WriteLine("In the operator");
        return new Int32Wrapper(lhs.value + rhs.value);
    }
}
class Test
{
    static void Main()
    {
        Int32Wrapper x = new Int32Wrapper(10);
        Int32Wrapper y = new Int32Wrapper(5);
        Int32Wrapper z = x + y;
        Console.WriteLine(z.Value); // 15
    }
}

回答你问题的最后一点:

这是否意味着在上面的ts = dt2 - dt1下面,有一个public static DateTime operator -(DateTime, DateTime)正在发生?

没有-没有DateTime减法运算符返回DateTime -只有一个返回TimeSpan

编辑:关于Point的第二个例子,我认为将两个Point值添加在一起在逻辑上是没有意义的。例如,如果将家庭位置添加到工作位置,会得到什么结果?使用Vector类型更有意义,然后:

public static Vector operator -(Point p1, Point p2)
public static Vector operator +(Vector v1, Vector v2)
public static Point operator +(Point p1, Vector v1)

假设你有一个名为Amount的类,如下所示:

public class Amount
{
    public int AmountInt { get; set; }
}

这个类有两个实例:

Amount am1 = new Amount { AmountInt = 2 };
Amount am2 = new Amount { AmountInt = 3 };

你不能简单地这样做:

Amount am3 = am1 + am2; //compilation error

必须在Amount类中添加一个操作符来提供这个功能:

public static Amount operator +(Amount amount1, Amount amount2)
{
    return new Amount { AmountInt = amount1.AmountInt + amount2.AmountInt };
}

减法(-)也是如此。现在如果你这样做:

Amount am3 = am1 + am2;
在本例中,am3的

int-value属性为5。希望这对你有帮助!

操作符只是一个方法的语法糖。例如,-操作符可以类似于

//not the actual syntax
public MyObject minus(MyObject object1, MyObject object2)
{
    //insert custom subtraction logic here
    return result
}

您可以为您定义的任何自定义类重载操作符。

这是我找到的一个教程

下面是本教程第一个示例的相关片段

   // Declare which operator to overload (+), the types 
   // that can be added (two Complex objects), and the 
   // return type (Complex):
   public static Complex operator +(Complex c1, Complex c2) 
   {
      return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
   }