C#:重载运算符

CLR 支持在类型中,通过使用operator定义静态成员函数来重载运算符,让开发人员可以像内置基元类型一样使用该类型。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Sum
    {
        public int Num { get; set; }
     
//重载运算符
//先写关键词public和static,operator关键词,操作符
public static Sum operator+ (Sum s1, Sum s2) { s2.Num =s2.Num + s1.Num;       //返回类型
return s2; } static void Main(string[] args) { Sum s1 = new Sum(); s1.Num = 10; Sum s2 = new Sum(); s2.Num = 20; // 实现
s2
+= s1; Console.WriteLine(s2.Num); // 30 Console.ReadKey(); } } }

<--@名词注释:

基元类型(primitive type):简单的说就是编译器直接支持的类型,如下:

sbyte / byte / short / ushort / int / uint / long / ulong

char / float / double / bool / decimal /object / string

编译器能够在基元类型之间进行显式或隐式转换。如果转换是安全的,也就是转换过程不会造成数据丢失,则可以直接采用隐式转换。如果是不安全的,则必须采用显式转换。

Int32 a=5; 
Int64 b=a; 
Int32 c=(Int32)b;

C#中的基元类型string实际上对应了System.String(FCL)类型,前者也就是后者的一别名,所以两者使用的时候没有什么不同。

-->

原文地址:https://www.cnblogs.com/Alvin-x/p/3231342.html