標籤:
8.1 以對象為成員
1.類的成員不光是可以使int,double等基本類型,也可以是其他類的對象;
class Program { static void Main(string[] args) { date d = new date(1992, 5, 18, new Time(12, 20, 5)); } } class date { int year; int month; int day; Time t; //(1)含有其他對象成員的類 public date(int year, int month, int day, Time t) { this.year = year; this.month = month; this.day = day; this.t = t; } } class Time { int houer; int minute; int second; public Time(int houer, int minute, int second ) { this.houer = houer; this.minute = minute; this.second = second; } }
8.2 靜態常量
(1)靜態變數就是用satic 關鍵字修飾的變數
(2)靜態變數只能使用類名引用不能使用對象調用
class Program { static void Main(string[] args) { S s = new S(); //s.number=5;// error (2)靜態變數只能使用類名引用不能使用對象調用 s.setSnumber(); Console.WriteLine(S.number); S.number = 4; Console.WriteLine(S.number); Console.ReadKey(); } } class S { public static int number; //(1)靜態變數就是用satic 關鍵字修飾的變數 public S() { number = 0; } public void setSnumber() { number = 5; } }
(3)靜態方法就是用satic 關鍵字修飾的方法
(4)靜態方法只能使用類名引用,不能使用對象引用
class Program { static void Main(string[] args) { A.print(); A a = new A(); //a.print(); error (2)靜態方法只能使用類名引用,不能使用對象引用 } } class A { public static void print() //(1)靜態方法就是用satic 關鍵字修飾的方法 { Console.WriteLine("print"); Console.ReadKey(); } }
8.3常量
8.3.1 const常量
(1)const 常量定義方法:存取權限+ const +類型+常量名=初始值;
(2)const 常量必須在定義時候同時賦值;
(3)const 常量是隱式靜態(不能用static關鍵字修飾),因此只能使用類名引用
class Program { static void Main(string[] args) { Console.WriteLine(circle.PI);//(3)const 常量是隱式靜態(不能用static關鍵字修飾),因此只能使用類名引用 Console.ReadKey(); } } class circle { // public const double PI ; (2)const 常量必須在定義時候同時賦值; // PI=3.14; public const double PI = 5;//(1)const 常量定義方法:存取權限+ const +類型+常量名=初始值; }
8.3.2 readonly常量
(1)readonly 常量定義方法:同const
(2)readonly 常量是非靜態常量,每個對象可以有不同的值,可以在建構函式中初始化(也可在定義時候賦值);
(3)由於readonly 常量是非靜態,和普通變數一樣,使用對象引用,不能使用類名引用
class Program { static void Main(string[] args) { hotel h1 = new hotel(20); hotel h2 = new hotel(30); Console.WriteLine(h1.number);//(3)由於readonly 常量是非靜態,和普通變數一樣,使用對象引用,不能使用類名引用 Console.WriteLine(h2.number); //Console.WriteLine(hotel.number); //error Console.ReadKey(); } }}class hotel{ public readonly int number=0;//(1)readonly 常量定義方法 public hotel(int number)//(2)readonly 常量是非靜態常量,每個對象可以有不同的值,可以在建構函式中初始化(也可在定義時候賦值); { this.number = number; }
8.4 重載
(1)函數名相同,參數個數或者參數類型不同 構成重載
(2)函數重載調用的原則是“首選”,系統或調用參數最匹配的那個函數
class Program { static void Main(string[] args) { //(2)函數重載調用的原則是“首選”,系統或調用參數最匹配的那個函數 Console.WriteLine(calculate.add(1,1)); Console.WriteLine(calculate.add(1.1, 1)); Console.WriteLine(calculate.add(1, 1,1)); Console.ReadKey(); } } class calculate { public static int add(int a, int b) { return a+b; } public static double add(double a, double b)//(1)函數名相同,參數個數或者參數類型不同 構成重載 { return a + b; } public static int add(int a, int b,int c) { return a + b+c; } }
8.5 待續
扣響C#之門筆記-第八章