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

发布于:2024-04-20 ⋅ 阅读:(23) ⋅ 点赞:(0)

总目录
C# 语法总目录

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

简介

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

面向对象编程

类 第三篇

9. 重载运算符
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 关键字

partial class PersonIntroduce
{
    partial void Add();
}
partial class PersonIntroduce
{    partial void Add()
    {

    }
}
** nameof方法 **

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

Person p = new Person();
string name = nameof(p);		//输出 p

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

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

Dog dog = new Dog();
Console.WriteLine(dog.GetType() == typeof(Dog));
** ToString方法 **

可以在类中重写该方法

结构体

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

结构体可以包含:

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

总目录
C# 语法总目录

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