当前位置:网站首页>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
publicandstaticModifier . - Unary operator has an input parameter . Binary operators have two input parameters . In each case , Must have at least one parameter of type
TorT?, amongTIs 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
边栏推荐
- 網上股票開戶安全嗎?是否可靠?
- [C supplement] [string] display the schedule of a month by date
- 徽商期货是正规期货平台吗?在徽商期货开户安全吗?
- [CF1476F]Lanterns
- Nearly 60% of the employees strongly support Ctrip's "3+2" working mode, and work at home for two days a week
- Easycvr accesses the equipment through the national standard gb28181 protocol. What is the reason for the automatic streaming of the equipment?
- Fresh, 2022 advanced Android interview must know 100 questions (interview questions + answer analysis)
- Unity3d extended toolbar
- Mujoco model learning record
- What impact will multinational encryption regulation bring to the market in 2022
猜你喜欢

SQL injection vulnerability (MySQL and MSSQL features)

. Net cloud native architect training camp (permission system code implements actionaccess) -- learning notes

June issue | antdb database participated in the preparation of the "Database Development Research Report" and appeared on the list of information technology and entrepreneurship industries

Penetration practice vulnhub range Nemesis

Thinkphp6 - CMS multi wechat management system source code

Computer network interview assault

Distributed task queue: Celery usage record

Penetration practice vulnhub range Tornado

From comedians to NBA Zhan Huang, check the encrypted advertisements during this super bowl

Data query language (DQL)
随机推荐
The difference and relationship between iteratible objects, iterators and generators
Penetration practice vulnhub range Tornado
Nielseniq found that 60% of the re launched products had poor returns
开发那些事儿:EasyCVR平台添加播放地址鉴权
Yuancosmos game farmersworld farmers world - core content of the second conference in China!
t10_ Adapting to Market Participantsand Conditions
Domestic spot silver should be understood
Definition of rotation axis in mujoco
Small exercise -- subnet division and summary
On the language internationalization of Yongzhong Office
Draw drawing process of UI drawing process
PIP version problems: PIP problems still occur when installing akshare and using Tsinghua source and Douban source
Length of learning and changing
[2. Basics of Delphi grammar] 4 Object Pascal operators and expressions
Explain in detail the process of realizing Chinese text classification by CNN
Gold, silver and four job hopping, interview questions are prepared, and Ali becomes the champion
The method of real-time tracking the current price of London Silver
Blackwich: the roadmap of decarbonization is the first step to realize the equitable energy transformation in Asia
Leetcode problem solving series -- continuous positive sequence with sum as s (sliding window)
The latest software scheme of the intelligent information management system of the armed police force