C#構造析構this重載賦值

記錄一下:
1.構造函數和析構函數:對對象進行初始化和回收對象資源。對象生命週期以構造函數開始,以析構函數結束。構造函數、析構函數與所在類具有相同名字,析構函數名前有(~),析構函數自動釋放對象所佔空間。
構造函數:
首先了解this保留字在類的構造函數中,this作爲值類型,它表示對正在構造的對象本身的應用。
析構函數:

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

namespace ConsoleApp3
{
    class Person
    {
        public string name;
        public int age;
        public int hight;
        //構造函數可以重載可以有多個,析構函數只有一個不可以重載,在函數全部運行後,析構函數自動調用。
        public Person()
        {
            name = "吳yx";
            age = 19;
            hight = 162;
        }
        public Person(string name,int age,int hight)
        {
            this.name = "張yx";
            this.age = 30;
            this.hight = 177;
        }
        //系統默認構造函數
        //public Person(){};
        ~Person ()
        {
            Console.WriteLine("析構函數調用");
        }
    }
    class Program
    {
        public  static void Main(string[] args)
        {
            Person t = new Person();//調用的是構造一。
            //Person t=new Person("吳yx",18,160);調用的是構造二。
            Console.WriteLine(t.name);
            Console.WriteLine(t.age);
            Console.WriteLine(t.hight);
            Console.ReadKey();
        }
    }
}

2方法體外定義變量
class program
{
public static d;
public static e;
public static void jiafa(int a,int b){d=a+b;e=a*b;}//方法
static void main(string[]args)
{
program.jiafa(4,2);
Console.WriteLine(program.d);
Console.WriteLine(program.e);
Console.ReadKey();
}
}
3方法的重載
滿足1方法名一樣2方法列表不一樣即可。(1類型2個數)
C#的乘法(重載)

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

namespace ConsoleApp3
{
    class Person
    {
        public int Sum(int a,int b)
        {
            return a * b;
        }
        public double Sum(double a, double b)
        {
            return a * b;
        }
        public int Sum(int a, int b, int c)
        {
            return a * b * c;
        }
    }
    class Program
    {
        public  static void Main(string[] args)
        {
            Person t = new Person();
            Console.WriteLine(t.Sum(6.5,9.7));
            Console.ReadKey();
        }
    }
}

4.類中可以賦所有初值、

namespace ConsoleApp3
{
    class Person
    {
        public string name="tdytdfy";
        public int age;
        public double hight;
        public double weight;
    }
  
    class Program
    {
        public  static void Main(string[] args)
        {
            Person t = new Person();
            t.name = "sda";
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章