当前位置:网站首页>C#入门系列(三十一) -- 运算符重载
C#入门系列(三十一) -- 运算符重载
2022-07-26 08:33:00 【InfoQ】
//修饰符 返回值类型 operator 可重载的运算符(参数列表)
public static Student operator +(Student a, Student b)
{
//方法体;
}
可重载和不可重载运算符
代码示例
using System;
namespace _6_2_1运算符重载
{
class Program
{
static void Main(string[] args)
{
Student st1 = new Student();
Student st2 = new Student();
Student st3 = new Student();
st1._acore = 40;
st2._acore = 50;
Console.WriteLine("st1和st2成绩是否相同:" + (st1 == st2));
Console.WriteLine("st1和st2成绩是否相同:" + (st1 != st2));
Console.WriteLine("运算前成绩:{0},{1},{2}", st1._acore, st2._acore, st3._acore);
//对象相加
st3 = st1 + st2;
//编译器自动重载+=
st1 += st2;
Console.WriteLine("运算后成绩:{0},{1},{2}",st1._acore,st2._acore,st3._acore);
Console.ReadKey();
}
}
class Student
{
private int acore;
public int _acore {
get { return acore; }
set { acore = value; }
}
//+重载: 对象加法,求得学生成绩和
public static Student operator +(Student b, Student c)
{
Student stu = new Student();
stu.acore = b.acore + c.acore;
return stu;
}
//当重载==时,必须重载!=,否则编译报错
public static bool operator ==(Student b , Student c)
{
bool result = false;
if(b.acore == c.acore)
{
result = true;
}
return result;
}
public static bool operator !=(Student b, Student c)
{
bool result = false;
if (b.acore != c.acore)
{
result = true;
}
return result;
}
}
}

边栏推荐
- JS tool function Encyclopedia
- Vscode domestic image server acceleration
- 【时间复杂度空间复杂度】
- 23.9 application exit application exit
- Mysql8 dual master and dual slave +mycat2 read / write separation
- Logic of data warehouse zipper table
- Mysql8 one master one slave +mycat2 read write separation
- 基于C语言设计的换乘指南打印系统
- Foundry教程:使用多种方式编写可升级的智能合约(上)
- Bee guitar score high octave and low octave
猜你喜欢

How to safely delete a useless activity in Android studio

Excel delete blank lines

基于C语言的内存管理-动态分区分配方式模拟

Mycat2 sub database and sub table

QSS add resource file of QT

Write common API tools swagger and redoc

Leetcode and query question summary

【搜索专题】看完必会的搜索问题之洪水覆盖

The second lesson is the construction of development environment

【时间复杂度空间复杂度】
随机推荐
Data validation typeerror: qiao Validate is not a function
[time complexity, space complexity]
P3743 kotori的设备
Kotlin variables and constants
Uninstallation of dual systems
Spark persistence strategy_ Cache optimization
22-07-16 personal training match 3 competition experience
BGP routing principle
memorandum...
Memory management based on C language - Simulation of dynamic partition allocation
Maximum common substring & regularity problem
shell编程
Random distribution learning notes
Why reserve a capacitor station on the clock output?
[endnote] detailed explanation of document template layout syntax
基于C#实现的文件管理文件系统
Mycat2 deploy master-slave MariaDB
Special lecture 2 dynamic planning learning experience (should be updated for a long time)
import error: ‘Icon‘ is not exported from ‘antd‘. Import icon error
How to safely delete a useless activity in Android studio