不需要同时重载前置和后置的operator++,你只要重载一次,public static T operator ++ (T obj)编译器自动给你解决前置和后置的问题

解决方案 »

  1.   

    也许我没说清楚,一般你只给struct类型重载operator++/--,那么你只要重载前置的即成,因为编译器自动给你处理后置的情形
      

  2.   

    class OpeTest {
    private int x;
    private int y;
    private int z; OpeTest(int x, int y, int z) {
    this.x = x;
    this.y = y;
    this.z = z;
    } OpeTest(OpeTest t) {
    x = t.x;
    y = t.y;
    z = t.z;
    } public static OpeTest operator ++(OpeTest t) {
    ++t.x; ++t.y; ++t.z;
    return t;
    }
    ... OpeTest a = new OpeTest(1, 2, 3);
    OpeTest b = new OpeTest(4, 5, 6); Console.WriteLine(++a);
    Console.WriteLine(b++);
    ...结果是2, 3, 4和5, 6, 7
    可我希望的结果是2, 3, 4和4, 5, 6
    后置的++运算和前置的一样成了先增后返回了
      

  3.   

    不需要重载前置的++/--,编译器可以帮助你正确完成工作。
    比如,你实现了MyType的operator++,那么
    mytype ++; 就等价于:
    return MyType.operator++(mytype);++mytype;就会等价于:
    MyType temp = mytype;
    MyType.operator++(mytype);
    return temp;这是C++里的标准实现,99%的C++类重载operator++(int i)是这样写的,所以C#算是reasonable的实现了。但是,要注意referenct type的operator++/--的实现,如果错了的话,前置operator就得不到期望的结果了。
      

  4.   

    果然把reference type的operator++实现错了。 
    正确的:
    public static OpeTest operator ++(OpeTest t) {
    OpeTest t1 = new OpeTest(t.x, t.y, t.z);
             ++t1.x; ++t1.y; ++t1.z;
    return t1;
    }其中到里应该容易想到的。:)
      

  5.   

    qqchen79(知秋一叶) :mytype ++; 就等价于:
    return MyType.operator++(mytype);++mytype;就会等价于:
    MyType temp = mytype;
    MyType.operator++(mytype);
    return temp;你是不是说反了?另外如果只要定义一个++,那么代码应该怎么写呢,能不能给个例子,如我上面所写的那样,就只能用作前置了
      

  6.   

    qqchen79(知秋一叶) :
    谢谢!但我还有一些疑问:
    public static OpeTest operator ++(OpeTest t) {
    return new OpeTest(t.x+1, t.y+1, t.z+1);
    }这样写法,对于效率上来说,不是太差了吗?
    无论先增或后增都要生成一个临时的对象?另外,对于比较等运算符,我这样写:
    public static bool operator ==(OpeTest lhs, OpeTest rhs) {
    return ((lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z));
    } public static bool operator !=(OpeTest lhs, OpeTest rhs) {
    return !(lhs == rhs);
    } public override bool Equals(object rhs) {
    if (rhs is OpeTest) {
    return this == (OpeTest)rhs;
    }
    return false;
    } public static bool operator <(OpeTest lhs, OpeTest rhs) {
    return ((lhs.x * lhs.x + lhs.y * lhs.y + lhs.z * lhs.z) < (rhs.x * rhs.x + rhs.y * rhs.y + rhs.z * rhs.z));
    } public static bool operator >(OpeTest lhs, OpeTest rhs) {
    return (rhs < lhs);
    } public static bool operator >=(OpeTest lhs, OpeTest rhs) {
    return !(lhs < rhs);
    } public static bool operator <=(OpeTest lhs, OpeTest rhs) {
    return !(lhs > rhs);
    }其中的!=,>,<=,>=等都是基于另一个函数调用的,这样写虽然避免了在程序修改时可能出现的前后代码不一致问题,但对于效率来说也是相当差的,不知C#中有没有与C++中inline相对应的东西,可以既无错又高效呢?
      

  7.   

    前一个问题好像没有什么办法,就看JIT Compiler有没有优化了(怀疑),而且只是前置操作副由性能损失。我觉得operator++这种东西即使在C++里也只能用在校的对象上,应该也有这种原因。后面一个其实你应该完全信赖JIT Compiler的,我跟过一段代码,多数小函数都被inline处理了(比如property的get/set)。即使在C++标准里,inline也不是硬性规定的,只是对compiler的“建议”,最后inline了没有还是有compiler决定的。