C艹——什么是类

一、什么是类?

1.类是一种数据结构(抽象的结果,抽象的载体)

类是一种数据结构,它可以包含数据成员(常量和字段)、函数成员(方法、事件、索引器、运算符、实例构造函数、静态构造函数和析构函数)以及嵌套类型。类类型支持继承,继承是一种机制,它使派生类可以对基类进行拓展和专用化

                                                                                                                                                                              ----《C#语言规范》

 

2.是一种数据类型 

类是一种引用类型,具体到每一个类上,都是一个自定义的类型

3.代表着现实世界中的“种类”

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

namespace HelloClass
{
    class Program
    {
        static void Main(string[] args)
        {
            // Student stu; //声明一个变量
            // Student stu = new Student() { ID =1,Name="Timothy"};//创建一个实例
            //若你不使用初始化器,得出的值会是0,这就默认构造器在起作用

            //Type t = typeof(Student);//反射基础
            //object o = Activator.CreateInstance(t, 2, "Parker");//会有类型丢失,无法使用Student的方法、属性,但可以找回
            //Student stu1 = o as Student;//找回类
            //Console.WriteLine(stu1.ID);//可以正常使用方法属性

            //Type t = typeof(Student);
            //dynamic stu2 = Activator.CreateInstance(t, 3, "pop");//dynamic编程
            //Console.WriteLine(stu2.Name);//不会有智能提示,但是找到Name



            Student s1 = new Student(1,"Timothy");
            Student s2 = new Student(2, "parker");
            Console.WriteLine(Student.Amount);
        }
       
    }

    class Student
    {
        public static int Amount { get; set; }//静态属性

       static Student()//静态构造器,用来初始化静态成员
        {
            Amount = 100;//student类一加载到内存之中就有100个  
        }

        ~Student()
        {
            Amount--;
            Console.WriteLine(Amount) ;//用完就-1
        }

        public Student(int id,string name)//ctor+tabx2,自己的构造器;名字要跟类名一样,长得很像方法但是没有返回值
        {
            this.ID = id;//ID就用传进来的值
            this.Name = name;
            Amount++;//有实例被创建就+1
        }
        ///类就像一个模板,有一个默认构造器,当我们想对一个实例进行个性化的时候,就自己造一个构造器进行修改
       
        //~Student()//处理垃圾内存的地方,程序使用完毕后就会调用析构器
        //{
        //    Console.WriteLine("Bye bye!Release the system resources..");
        //}

        public int ID { get; set; }
        public string Name { get; set; }
        public void Report()
        {
            Console.WriteLine($"I'm #{ID} student,my name is {Name}");
        }
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值