我想要超载++
运算符在我的 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();
}
}
}
您的示例无法正确实现此一元运算符,如 C# 规范中所指定17.9.1 一元运算符 :
与 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)