c#中重载单目运算符-
Here, we will design overloaded methods for unary increment (++) and decrement (--). In the below program, we will create a class Sample, with data member val.
在这里,我们将为一进制增量(++)和减量(-)设计重载方法。 在下面的程序中,我们将创建一个类Sample ,其数据成员为val 。
using System;
namespace ConsoleApplication1
{
class Sample
{
//declare integer data member
private int val;
//initialize data members
public Sample(int val)
{
this.val = val;
}
//Overload unary decrement operator
public static Sample operator --(Sample S)
{
S.val = --S.val;
return S;
}
//Overload unary increment operator
public static Sample operator ++(Sample S)
{
S.val = ++S.val;
return S;
}
public void PrintValues()
{
Console.WriteLine("Values of val: " + val);
Console.WriteLine();
}
}
class Program
{
static void Main(string[] args)
{
Sample S = new Sample(10);
S++;
S++;
S++;
S.PrintValues();
S--;
S--;
S.PrintValues();
}
}
}
Output
输出量
Values of val: 13
Values of val: 11
c#中重载单目运算符-