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

总目录
C# 语法总目录

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

简介

  主要记录的是面向对象编程中,类的解构器,方法的使用,索引器和终结器及相关的注意事项

面向对象编程

类 第二篇

4. 解构器

要求C# 7.0以上

这里的解构器可以看做是构造器的反向操作,解构器可以把一个对象赋值给一个元组

解构器必须要下面这种形式,必须是Deconstruct这个名字,必须要有out传出参数。

public void Deconstruct(out string? name,out int age)

internal class Person
{
    private string? name;
    private int age;
    public Person()
    {
        name = "zhang";
        age = 18;
    }

    public Person(string? name,int age)
    {
        this.name = name;
        this.age = age;
    }

    public string? Name { get => name; set => name = value; }
    public int Age { get => age; set => age = value; }

    //必须要
    public void Deconstruct(out string? name,out int age)
    {
        name = Name;
        age = Age;
    }

    public override string ToString()
    {
        return this.name+","+this.age;
    }
}
static void Main(string[] args)
{
    Person p = new Person();
    (string? name, int age) = p;
    Console.WriteLine(name+","+age);
    Console.ReadLine();
}
//输出
zhang,18
5.方法

方法可以用以下修饰符修饰

  • 静态修饰符:Static
  • 访问修饰符:public , internal , private , protected
  • 继承修饰符:new , virtual , abstract, override , sealed
  • 部分方法修饰符: partial
  • 非托管代码修饰符:unsafe , extern
  • 异步代码修饰符:async

其他比如重载方法,使用 ref 引用传递,过程略。

6. 事件

需要搭配委托使用,暂略。

7. 索引器

索引器一般是数组用的东西,但是类中也有这个方法。

简单来说,类的索引器就是重写 [ ] 中括号这个

internal class PersonIntroduce
{
    private string? content;
    private string[]? conts;

    public PersonIntroduce()
    {
        content = "this is introduce";
        conts = content.Split();
    }

    public PersonIntroduce(string content)
    {
        this.content = content;
        conts = content.Split();
    }

    public string this[int index]
    {
        get { return conts[index]; }
        set { conts[index] = value; }
    }
}
static void Main(string[] args)
{
    PersonIntroduce pi = new PersonIntroduce();
    string str = pi[1];
    Console.WriteLine(str);
    pi[1] = "times";
    Console.WriteLine(pi[1]);
    Console.ReadLine();
}
//输出
is
times
8. 终结器

终结器(Finalizer),在垃圾回收器回收未引用的对象占用的内存前调用。

终结器可以被 非托管代码修饰符 unsafe 修饰。

internal class PersonIntroduce
{
    public PersonIntroduce()
    {
        Console.WriteLine("开始");
    }
    ~PersonIntroduce(){
        Console.WriteLine("结束了");
    }
}
static void Main(string[] args)
{
    PersonIntroduce pi = new PersonIntroduce();
   
}

总目录
C# 语法总目录

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

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值