如何在我的班级中实现前后递增/递减运算符?

cha*_*987 2 c# operator-overloading

我想++在我的c#类中使用运算符重载来重载运算符以使用预增量和后增量.但只有后增量才有效.如何使这两个功能在我班上工作?假设我做了一个类ABC -

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

namespace Test
{
    class ABC
    {
      public int a,b;
      public ABC(int x, int y)
      {
        a = x;
        b = y;
      }
      public static ABC operator ++(ABC x)
      {
        x.a++;
        x.b++;
        return x;
      }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ABC a = new ABC(5, 6);
            ABC b, c;
            b = a++;
            Console.WriteLine("After post increment values are {0} and {1} and values of b are {2} and {3}", a.a, a.b, b.a, b.b);// expected output a.a = 6, a.b = 7, b.a = 5, b.b = 6 but not get that
            c = ++a;
            Console.WriteLine("After pre increment values are {0} and {1} and values of c are {2} and {3}", a.a, a.b, c.a, c.b); // expected output a.a = 7, a.b = 7, c.a = 7, c.b = 8 works fine
            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*lia 5

您的示例无法正确实现此一元运算符,如17.9.1一元运算符中的C#规范所指定:

与C++不同,此方法不需要,事实上,不应该直接修改其操作数的值.

这是您的样本与一些微单元测试:

using System;

class ABC
{
  public int a,b;
  public ABC(int x, int y)
  {
    a = x;
    b = y;
  }

  public static ABC operator ++(ABC x)
  {
    x.a++;
    x.b++;
    return x;
  }
}

class Program
{
    static void Main()
    {
        var a = new ABC(5, 6);
        if ((a.a != 5) || (a.b != 6)) Console.WriteLine(".ctor failed");

        var post = a++;
        if ((a.a != 6) || (a.b != 7)) Console.WriteLine("post incrementation failed");
        if ((post.a != 5) || (post.b != 6)) Console.WriteLine("post incrementation result failed");

        var pre = ++a;
        if ((a.a != 7) || (a.b != 8)) Console.WriteLine("pre incrementation failed");
        if ((pre.a != 7) || (pre.b != 8)) Console.WriteLine("pre incrementation result failed");

        Console.Read();
    }
}
Run Code Online (Sandbox Code Playgroud)

您的代码失败是后增量结果,这是因为您更改了作为参数传递的ABC实例而不是返回新实例.更正代码:

class ABC
{
  public int a,b;
  public ABC(int x, int y)
  {
    a = x;
    b = y;
  }

  public static ABC operator ++(ABC x)
  {
    return new ABC(x.a + 1, x.b + 1);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 哦,我的上帝!这样的记忆浪费! (3认同)