当前位置:网站首页>C operator overloads the query table
C operator overloads the query table
2022-07-01 18:23:00 【KeithPro】
There is a problem in the process of project development , The team previously made a lot of non empty judgments on a very low-level base class when writing programs , Later, in the later development, it was found that this kind of unreliable , There is a problem , Need to replace all , wow , When will thousands of files have to be found , Finally, one of them proposed a method , Overload the base class judgment method , The author found that some operations can be overloaded , Some operations cannot be overloaded , Here is a record of the overloaded operator table officially provided by Microsoft , For later use , Also prevent yourself from forgetting ( Now this memory is far from good )
User defined types can overload predefined C# Operator . in other words , When one or both operands are of a certain type , This type provides a custom implementation of the operation . Overloadable operators What is introduced in section C# Operators can be overloaded .
Use operator
Keyword to declare operators . Operator declarations must conform to the following rules :
- Also include
public
andstatic
Modifier . - Unary operator has an input parameter . Binary operators have two input parameters . In each case , Must have at least one parameter of type
T
orT?
, amongT
Is a type that contains operator declarations .
The following example defines a simple structure for representing rational numbers . This structure will overload some Arithmetic operator :
using System;
public readonly struct Fraction
{
private readonly int num;
private readonly int den;
public Fraction(int numerator, int denominator)
{
if (denominator == 0)
{
throw new ArgumentException("Denominator cannot be zero.", nameof(denominator));
}
num = numerator;
den = denominator;
}
public static Fraction operator +(Fraction a) => a;
public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den);
public static Fraction operator +(Fraction a, Fraction b)
=> new Fraction(a.num * b.den + b.num * a.den, a.den * b.den);
public static Fraction operator -(Fraction a, Fraction b)
=> a + (-b);
public static Fraction operator *(Fraction a, Fraction b)
=> new Fraction(a.num * b.num, a.den * b.den);
public static Fraction operator /(Fraction a, Fraction b)
{
if (b.num == 0)
{
throw new DivideByZeroException();
}
return new Fraction(a.num * b.den, a.den * b.num);
}
public override string ToString() => $"{num} / {den}";
}
public static class OperatorOverloading
{
public static void Main()
{
var a = new Fraction(5, 4);
var b = new Fraction(1, 2);
Console.WriteLine(-a); // output: -5 / 4
Console.WriteLine(a + b); // output: 14 / 8
Console.WriteLine(a - b); // output: 6 / 8
Console.WriteLine(a * b); // output: 5 / 8
Console.WriteLine(a / b); // output: 10 / 4
}
}
Operator | Heavy duty |
---|---|
+x、-x、!x、~x、++、--、true、false | These unary operators can be overloaded . |
x + y、x - y、x * y、x / y、x % y、x & y、x | y、x ^ y、x << y, x >> y、x == y、x != y、x < y, x > y、x <= y, x >= y | These binary operators can be overloaded . Some operators must be overloaded in pairs ; For more information , Please check the notes at the back of this form . |
x && y、x || y | Cannot overload conditional logical operators . however , If you have overloaded true and false Operator The type of is also overloaded in some way & or | Operator , Can be calculated separately for this type of operand && or || Operator . For more information , see also C# language norm Of User defined conditional logical operators part . |
a[i], a?[i] | Element access is not considered a reloadable operator , But you can define Indexer . |
(T)x | Cast operators cannot be overloaded , But you can define custom type conversions that can be performed by cast expressions . For more information , see also User defined conversion operators . |
+=、-=、*=、/=、%=、&=、|=、^=、<<=, >>= | Compound assignment operators cannot be explicitly overloaded . But when overloading binary operators , The corresponding compound assignment operator will also be implicitly overloaded ( If you have any ). for example , Use + ( Can be overloaded ) Calculation += . |
^x、x = y、x.y、x?.y、c ? t : f、x ?? y、x ??= y、x..y、x->y、=>、f(x)、as、await、checked、unchecked、default、delegate、is、nameof、new、sizeof、stackalloc、switch、typeof、with | These operators cannot be overloaded . |
remarks
Comparison operators must be overloaded in pairs . in other words , If you overload any one of a pair of operators , Then the other operator must also be overloaded . Such pairing is shown below :
==
and!=
Operator<
and>
Operator<=
and>=
Operator
边栏推荐
- Vue uses keep alive to cache page optimization projects
- Check log4j problems using stain analysis
- MFC obtains local IP (used more in network communication)
- Distributed task queue: Celery usage record
- How to retrieve the password for opening Excel files
- Debiasing word embeddings | talking about word embedding and deviation removal # yyds dry goods inventory #
- Is online stock account opening safe? Is it reliable?
- 【Try to Hack】vulnhub DC4
- Smart factory digital management system software platform
- 期货账户的资金安全吗?怎么开户?
猜你喜欢
. Net cloud native architect training camp (permission system code implements actionaccess) -- learning notes
[C supplement] [string] display the schedule of a month by date
Distributed task queue: Celery usage record
Length of learning and changing
Thinkphp6 - CMS multi wechat management system source code
Localization through custom services in the shuttle application
Cloud picture says | distributed transaction management DTM: the little helper behind "buy buy buy"
[beauty detection artifact] come on, please show your unique skill (is this beauty worthy of the audience?)
Rotation order and universal lock of unity panel
Leetcode 1380. Lucky numbers in the matrix (save the minimum number of each row and the maximum number of each column)
随机推荐
On the language internationalization of Yongzhong Office
Is the fund of futures account safe? How to open an account?
ZABBIX alarm execute remote command
EasyCVR设备录像出现无法播放现象的问题修复
Relationship between sensor size, pixel, dpi resolution, inch and millimeter
From comedians to NBA Zhan Huang, check the encrypted advertisements during this super bowl
網上股票開戶安全嗎?是否可靠?
Blackwich: the roadmap of decarbonization is the first step to realize the equitable energy transformation in Asia
传感器尺寸、像素、DPI分辨率、英寸、毫米的关系
Debiasing word embeddings | talking about word embedding and deviation removal # yyds dry goods inventory #
Bug of QQ browser article comment: the commentator is wrong
EasyCVR通过国标GB28181协议接入设备,出现设备自动拉流是什么原因?
LeetCode 148. Sort linked list
网上股票开户安全吗?是否可靠?
Definition of rotation axis in mujoco
Penetration practice vulnhub range Nemesis
Intel's open source deep learning tool library openvino will increase cooperation with local software and hardware parties and continue to open
Vue uses keep alive to cache page optimization projects
Function, condition, regular expression
t10_ Adapting to Market Participantsand Conditions