当前位置:网站首页>C# operator
C# operator
2022-04-21 17:53:00 【我把生活交给了工作】
使用 operator 关键字来重载内置运算符,或提供类或结构声明中的用户定义转换。
示例
下面是分数的一个极其简化的类。该类重载了 + 和 * 运算符,以执行分数加法和乘法;同时提供了将 Fraction 类型转换为 double 类型的转换运算符。
// cs_keyword_operator.cs
using System;
class Fraction
{
int num, den;
public Fraction(int num, int den)
{
this.num = num;
this.den = den;
}
// overload operator +
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.num * b.den + b.num * a.den,
a.den * b.den);
}
// overload operator *
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.num * b.num, a.den * b.den);
}
// user-defined conversion from Fraction to double
public static implicit operator double(Fraction f)
{
return (double)f.num / f.den;
}
}
class Test
{
static void Main()
{
Fraction a = new Fraction(1, 2);
Fraction b = new Fraction(3, 7);
Fraction c = new Fraction(2, 3);
Console.WriteLine((double)(a * b + c));
}
}
输出
0.880952380952381
版权声明
本文为[我把生活交给了工作]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44231544/article/details/124281632
边栏推荐
- How to turn on the undisturbed time with win10 memo how to set the message of rest day to be undisturbed
- 使用K3S创建本地开发集群
- Huawei URPF
- What happens when the user sends a request to execute the controller method
- Logstash ~ execution model of logstash
- 什么是 ODBC – 开放式数据库连接
- 短视频平台搭建,仿制一个登陆界面的demo
- Insight technology passed the "federal learning" product evaluation of the national financial technology evaluation center of the central bank in the first batch, realizing the dual certification of "
- 动态规划:硬币题目总结
- onnx效率问题:和Module & DataParallel比较
猜你喜欢

头条自媒体运营秘籍,坚持下去你就可以打败90%的人

What is ODBC – open database connectivity

Thesis | attention based bidirectional long short term memory networks for relation classification
How to turn on the undisturbed time with win10 memo how to set the message of rest day to be undisturbed

Chest X-ray images - dataset

深耕行业数十年,多元视角解读!从思维转变看数字化转型 IT 经营

终于完成学生时代的梦想-制作掌机用单片机STM32手把手教你

看看技术宅怎么拯救学霸机,我用10块钱修好了笔记本电脑

MySQL基础合集
Introduction to MySQL ODBC driver
随机推荐
Akismet plugin tutorial WordPress prevent spam filtering plugin
torch.max()的用法
About riched32 DLL Trojan horse
Logstash ~ how logstash works
【C语言重难点突破】——动态内存管理
短视频平台搭建,仿制一个登陆界面的demo
Mobile date plug-in (add your favorite)
Shell programming learning (III) condition judgment and process control
Is qiniu financial management useful? Is it safe?
干货|app自动化测试之Appium 源码分析
C# ODBC将一个文件夹的文件装载到PostgreSQL数据库BLOB列,并将BLOB列下载到另一个文件夹
There is a prize for essay | a heavy prize of 5000 yuan. You are invited to contribute
What is ODBC – open database connectivity
直播带货源码,渐变式状态栏的不同写法
Brief introduction of common methods of wireless DoS attack
LogStash~LogStash的配置文件
Small fuzzy query, unexpectedly modified the code three times back and forth? Find an electronics factory
onnx效率问题:和Module & DataParallel比较
MySQL基础合集
Pytorch数据封装进入网络前的几种方式