[C#基础]C#中的重载运算符
来源:互联网 发布:淘宝副总裁 编辑:程序博客网 时间:2024/05/16 10:05
本文转自:http://blog.csdn.net/ecidevilin/article/details/53401006,请点击链接查看原文,尊重楼主版权。
C#里使用Operator关键字定义静态方法来重载运算符:
e.g.
public class TestPoint { public TestPoint(int x_, int y_) { x = x_; y = y_; } public int x; public int y; public static TestPoint operator++ (TestPoint pt) { return new TestPoint (pt.x + 1, pt.y + 1); } public static TestPoint operator-- (TestPoint pt) { return new TestPoint (pt.x - 1, pt.y - 1); } public static TestPoint operator+ (TestPoint pt1, TestPoint pt2) { return new TestPoint (pt1.x + pt2.x, pt1.y + pt2.y); } public static bool operator== (TestPoint pt1, TestPoint pt2) { return pt1.x == pt2.x && pt1.y == pt2.y; } public static bool operator!= (TestPoint pt1, TestPoint pt2) { return !(pt1 == pt2); } public override string ToString() { return string.Format("{0} , {1}", this.x, this.y); } public int this[int idx] { get { if (idx == 0) { return x; } else if (idx == 1) { return y; } else { throw new System.IndexOutOfRangeException (); } } set { if (idx == 0) { x = value; } else if (idx == 1) { y = value; } else { throw new System.IndexOutOfRangeException (); } } } }使用:
var tp1 = new TestPoint (1, 2);Console.WriteLine (tp1++);Console.WriteLine (++tp1);Console.WriteLine (tp1);var tp2 = new TestPoint (10, 20);Console.WriteLine (tp1 + tp2);tp1 += tp2;Console.WriteLine (tp1);tp1 [1] = 55;Console.WriteLine (tp1);Console.WriteLine (tp2[0]);Console.WriteLine (tp1 != tp2);
+ -
! ~
++ --
true false这些一元运算符可以进行重载。+ - * / %
& |
^
<< >>这些二元运算符可以进行重载。== !=
< >
<= >=比较运算符可以进行重载
如果进行重载,则必须成对进行重载。
即如果重载
==
,也必须重载!=
, 反之亦然。对于
<
和 >
以及 <=
和 >=
也是同理。&& ||逻辑运算符无法进行重载,但是它们使用 & 和
|
来计算。[]索引运算符无法进行重载。但是可以定义索引器
(参考C#语法小知识(六)属性与索引器)。(T)x强制转换运算符无法进行重载。
但是可以使用explicit 和 implicit定义转换运算符。
(参考C#语法小知识(二十四)自定义类型转换)
+= -= *= /= %=&= |=
^=
<<= >>=赋值运算符无法进行重载。
但是它们使用对应的非赋值运算符来计算(例如+=使用了+)。=
.
?: ??
-> =>
f(x)
as is
checked unchecked
default
delegate
new sizeof typeof这些运算符无法进行重载。
阅读全文
0 0
- [C#基础]C#中的重载运算符
- c#中的运算符重载
- C#中的运算符重载
- c#基础 运算符的重载
- 介绍 C# 中的运算符重载
- C#运算符重载
- C# - 运算符重载
- C#运算符重载
- c#运算符重载
- C# 运算符重载
- C#运算符重载
- C# 运算符重载
- C#运算符重载
- C#重载运算符
- C#运算符重载
- C#运算符重载
- C#运算符重载
- C#运算符重载
- 计步器初步构思
- Linux C之进程间通讯
- 阶乘的几种表示方法及其拓展
- 简单的排序问题
- python里使用enum库枚举类型的比较(二)
- [C#基础]C#中的重载运算符
- 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
- 【操作系统】文件的逻辑结构
- Linux系统之firewalld
- centos安装pip
- 使用tmux分屏(既可以左右分屏,也可以上下分屏)
- iOStableview手势冲突
- codeforces 886D. Restoration of string (字符串处理+类拓扑排序)
- 变化检测的基础算法与实现