17.9.1 Unary operators

The following rules apply to unary operator declarations, where T denotes
the class or struct type that contains
the operator declaration:
? A unary +, -, !, or ~ operator must take a single parameter of type T and
can return any type.
? A unary ++ or -- operator must take a single parameter of type T and must
return type T.
? A unary true or false operator must take a single parameter of type T and
must return type bool.
The signature of a unary operator consists of the operator token (+, -, !,
~, ++, --, true, or false) and the type
of the single formal parameter. The return type is not part of a unary
operator?s signature, nor is the name of the
formal parameter.
C# LANGUAGE SPECIFICATION
256
The true and false unary operators require pair-wise declaration. A
compile-time error occurs if a class
declares one of these operators without also declaring the other. The true
and false operators are described
further in §14.16.
[Example: The following example shows an implementation and subsequent
usage of operator++ for an integer
vector class:
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
}
}
Note how the operator method returns the value produced by adding 1 to the
operand, just like the postfix
increment and decrement operators(§14.5.9), and the prefix increment and
decrement operators (§14.6.5). Unlike
in C++, this method need not, and, in fact, must not, modify the value of
its operand directly. end example]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值