C# 面向对象编程(一)——类 第三篇

总目录
C# 语法总目录
系列链接
C# 面向对象编程(一) 类 第一篇
C# 面向对象编程(一) 类 第二篇
C# 面向对象编程(一) 类 第三篇

C# 面向对象编程 一 ------类 第三篇

    • 简介
    • 面向对象编程
      • [类 第三篇](#类 第三篇)
        • [9. 重载运算符](#9. 重载运算符)
        • [10. 分部方法](#10. 分部方法)
        • [** nameof方法 **](#** nameof方法 **)
        • [** GetType 方法和 typeof方法 **](#** GetType 方法和 typeof方法 **)
        • [** ToString方法 **](#** ToString方法 **)
      • 结构体

简介

主要记录的是面向对象编程中,类重载运算符,分部方法的使用和一些常用方法,以及结构体的一些注意事项

面向对象编程

类 第三篇

9. 重载运算符
csharp 复制代码
internal class PersonIntroduce
{
    private int a;
    public int A { get => a; set => a = value; }
    public PersonIntroduce()
    {
        a = 1;
    }
    ~PersonIntroduce()
    {
        Console.WriteLine("结束了");
    }

    public static PersonIntroduce operator +(PersonIntroduce a, PersonIntroduce b)
    {
        PersonIntroduce per = new PersonIntroduce();
        per.a = a.a + b.a;
        return per;
    }
}
static void Main(string[] args)
{
    PersonIntroduce pi = new PersonIntroduce();
    PersonIntroduce pj = new PersonIntroduce();
    Console.WriteLine((pi + pj).A); 
   
}
//输出
2
10. 分部方法

方法的声明和定义可以在不同文件里面,但是需要再同一个命名空间,添加 partial 关键字

csharp 复制代码
partial class PersonIntroduce
{
    partial void Add();
}
partial class PersonIntroduce
{    partial void Add()
    {

    }
}
** nameof方法 **

可以返回任意类型 或者成员 或者变量的字符串名称

csharp 复制代码
Person p = new Person();
string name = nameof(p);		//输出 p

int num = 10;
string name = nameof(num);		//输出 num
** GetType 方法和 typeof方法 **

使用这个两个方法可以获取当前对象的类,两个都是返回的 System.Type 类型

csharp 复制代码
Dog dog = new Dog();
Console.WriteLine(dog.GetType() == typeof(Dog));
** ToString方法 **

可以在类中重写该方法

结构体

结构体和类相比,结构体是值类型,类是引用类型。结构体无法继承。

结构体可以包含:

  • 字段初始化器
  • 无参数的构造器
  • 终结器
  • 虚成员或 protected 成员
csharp 复制代码
public struct Point{
    int x,y;
    public Point(int x,int y){ this.x = x; this.y = y;}
}

总目录
C# 语法总目录
系列链接
C# 面向对象编程(一) 类 第一篇
C# 面向对象编程(一) 类 第二篇
C# 面向对象编程(一) 类 第三篇

相关推荐
晨星shine3 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530143 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526743 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526743 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang4 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf7 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530147 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools8 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的9 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21889 天前
.NET 本地Db数据库-技术方案选型
windows·c#