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

时间:2010-07-19 15:44:34

标签: 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();
        }
    }
}

2 个答案:

答案 0 :(得分: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();
    }
}

您的代码失败是后增量结果,这是因为您更改了作为参数传递的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);
  }
}

答案 1 :(得分:1)

以下是规范中的示例,您的情况有何不同?

public class IntVector 
{ 
    public int Length { … }    // read-only property 
    public int this[int index] { … } // read-write indexer 
    public IntVector(int vectorLength) { … } 
    public static IntVector operator++(IntVector iv) { 
        IntVector temp = new IntVector(iv.Length); 
        for (int i = 0; i < iv.Length; ++i) 
            temp[i] = iv[i] + 1; 
        return temp; 
    } 
} 
class Test 
{ 
    static void Main() { 
        IntVector iv1 = new IntVector(4); // vector of 4x0 
        IntVector iv2; 

        iv2 = iv1++; // iv2 contains 4x0, iv1 contains 4x1 
        iv2 = ++iv1; // iv2 contains 4x2, iv1 contains 4x2 
    } 
}