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# 面向对象编程(一) 类 第三篇

相关推荐
咕白m6251 小时前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902112 小时前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠19 小时前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫3 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech3 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf5 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6255 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech5 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0066 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术6 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript