前面幾篇部落格介紹了C#的一些基礎知識,包括基本語法、資料型別、運運算元等。在本篇部落格就來介紹在C#中最常用的幾種資料型別——陣列、字串、結構體、列舉、類
陣列是一個儲存相同型別元素的固定大小的順序集合。陣列是用來儲存資料的集合,通常認為陣列是一個同一型別變數的集合。
宣告陣列變數並不是宣告 number0、number1、…、number99 一個個單獨的變數,而是宣告一個就像 numbers 這樣的變數,然後使用 numbers[0]、numbers[1]、…、numbers[99] 來表示一個個單獨的變數。陣列中某個指定的元素是通過索引來存取的。
所有的陣列都是由連續的記憶體位置組成的。最低的地址對應第一個元素,最高的地址對應最後一個元素。
在 C# 中宣告一個陣列,您可以使用下面的語法:
datatype[] arrayName;
其中,
例如:
double[] balance;
宣告一個陣列不會在記憶體中初始化陣列。當初始化陣列變數時,您可以賦值給陣列。
陣列是一個參照型別,所以您需要使用 new 關鍵字來建立陣列的範例。
例如:
double[] balance = new double[10];
可以通過使用索引號賦值給一個單獨的陣列元素,比如:
double[] balance = new double[10];
balance[0] = 4500.0;
可以在宣告陣列的同時給陣列賦值,比如:
double[] balance = { 2340.0, 4523.69, 3421.0};
也可以建立並初始化一個陣列,比如:
int [] marks = new int[5] { 99, 98, 92, 97, 95};
在上述情況下,你也可以省略陣列的大小,比如:
int [] marks = new int[] { 99, 98, 92, 97, 95};
也可以賦值一個陣列變數到另一個目標陣列變數中。在這種情況下,目標和源會指向相同的記憶體位置:
int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;
當建立一個陣列時,C# 編譯器會根據陣列型別隱式初始化每個陣列元素為一個預設值。例如,int 陣列的所有元素都會被初始化為 0。
元素是通過帶索引的陣列名稱來存取的。這是通過把元素的索引放置在陣列名稱後的方括號中來實現的。例如:
double salary = balance[9];
下面是一個範例,使用上面提到的三個概念,即宣告、賦值、存取陣列:
範例
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n 是一個帶有 10 個整數的陣列 */
int i,j;
/* 初始化陣列 n 中的元素 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}
/* 輸出每個陣列元素的值 */
for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
在前面的範例中,我們使用一個 for 迴圈來存取每個陣列元素。也可以使用一個 foreach 語句來遍歷陣列。
範例
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n 是一個帶有 10 個整數的陣列 */
/* 初始化陣列 n 中的元素 */
for ( int i = 0; i < 10; i++ )
{
n[i] = i + 100;
}
/* 輸出每個陣列元素的值 */
foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
在 C# 中,陣列是非常重要的,且需要了解更多的細節。下面列出了 C# 程式設計師必須清楚的一些與陣列相關的重要概念:
概念 | 描述 |
---|---|
多維陣列 | C# 支援多維陣列。多維陣列最簡單的形式是二維陣列。 |
交錯陣列 | C# 支援交錯陣列,即陣列的陣列。 |
傳遞陣列給函數 | 可以通過指定不帶索引的陣列名稱來給函數傳遞一個指向陣列的指標。 |
引數陣列 | 這通常用於傳遞未知數量的引數給函數。 |
Array 類 | 在 System 名稱空間中定義,是所有陣列的基礎類別,並提供了各種用於陣列的屬性和方法。 |
在 C# 中,您可以使用字元陣列來表示字串,但是,更常見的做法是使用 string 關鍵字來宣告一個字串變數。string 關鍵字是 System.String 類的別名。
建立 String 物件
可以使用以下方法之一來建立 string 物件:
範例
using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//字串,字串連線
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
string fullname = fname + lname;
Console.WriteLine("Full Name: {0}", fullname);
//通過使用 string 建構函式
char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);
//方法返回字串
string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);
//用於轉化值的格式化方法
DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
string chat = String.Format("Message sent at {0:t} on {0:D}",
waiting);
Console.WriteLine("Message: {0}", chat);
Console.ReadKey() ;
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Full Name: RowanAtkinson
Greetings: Hello Message: Hello
From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012
String 類有以下兩個屬性:
序號 | 屬性名稱 & 描述 |
---|---|
1 | Chars 在當前 String 物件中獲取 Char 物件的指定位置。 |
2 | Length 在當前的 String 物件中獲取字元數。 |
String 類有許多方法用於 string 物件的操作。下面的表格提供了一些最常用的方法:
序號 | 方法名稱 &描述 |
---|---|
1 | public static int Compare( string strA, string strB ) 比較兩個指定的 string 物件,並返回一個表示它們在排列順序中相對位置的整數。該方法區分大小寫。 |
2 | public static int Compare( string strA, string strB, bool ignoreCase ) 比較兩個指定的 string 物件,並返回一個表示它們在排列順序中相對位置的整數。但是,如果布林引數為真時,該方法不區分大小寫。 |
3 | public static string Concat( string str0, string str1 ) 連線兩個 string 物件。 |
4 | public static string Concat( string str0, string str1, string str2 ) 連線三個 string 物件。 |
5 | public static string Concat( string str0, string str1, string str2, string str3 ) 連線四個 string 物件。 |
6 | public bool Contains( string value ) 返回一個表示指定 string 物件是否出現在字串中的值。 |
7 | public static string Copy( string str ) 建立一個與指定字串具有相同值的新的 String 物件。 |
8 | public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) 從 string 物件的指定位置開始複製指定數量的字元到 Unicode 字元陣列中的指定位置。 |
9 | public bool EndsWith( string value ) 判斷 string 物件的結尾是否匹配指定的字串。 |
10 | public bool Equals( string value ) 判斷當前的 string 物件是否與指定的 string 物件具有相同的值。 |
11 | public static bool Equals( string a, string b ) 判斷兩個指定的 string 物件是否具有相同的值。 |
12 | public static string Format( string format, Object arg0 ) 把指定字串中一個或多個格式項替換為指定物件的字串表示形式。 |
13 | public int IndexOf( char value ) 返回指定 Unicode 字元在當前字串中第一次出現的索引,索引從 0 開始。 |
14 | public int IndexOf( string value ) 返回指定字串在該範例中第一次出現的索引,索引從 0 開始。 |
15 | public int IndexOf( char value, int startIndex ) 返回指定 Unicode 字元從該字串中指定字元位置開始搜尋第一次出現的索引,索引從 0 開始。 |
16 | public int IndexOf( string value, int startIndex ) 返回指定字串從該範例中指定字元位置開始搜尋第一次出現的索引,索引從 0 開始。 |
17 | public int IndexOfAny( char[] anyOf ) 返回某一個指定的 Unicode 字元陣列中任意字元在該範例中第一次出現的索引,索引從 0 開始。 |
18 | public int IndexOfAny( char[] anyOf, int startIndex ) 返回某一個指定的 Unicode 字元陣列中任意字元從該範例中指定字元位置開始搜尋第一次出現的索引,索引從 0 開始。 |
19 | public string Insert( int startIndex, string value ) 返回一個新的字串,其中,指定的字串被插入在當前 string 物件的指定索引位置。 |
20 | public static bool IsNullOrEmpty( string value ) 指示指定的字串是否為 null 或者是否為一個空的字串。 |
21 | public static string Join( string separator, string[] value ) 連線一個字串陣列中的所有元素,使用指定的分隔符分隔每個元素。 |
22 | public static string Join( string separator, string[] value, int startIndex, int count )連線接一個字串陣列中的指定位置開始的指定元素,使用指定的分隔符分隔每個元素。 |
23 | public int LastIndexOf( char value )返回指定 Unicode 字元在當前 string 物件中最後一次出現的索引位置,索引從 0 開始。 |
24 | public int LastIndexOf( string value ) 返回指定字串在當前 string 物件中最後一次出現的索引位置,索引從 0 開始。 |
25 | public string Remove( int startIndex ) 移除當前範例中的所有字元,從指定位置開始,一直到最後一個位置為止,並返回字串。 |
26 | public string Remove( int startIndex, int count ) 從當前字串的指定位置開始移除指定數量的字元,並返回字串。 |
27 | public string Replace( char oldChar, char newChar ) 把當前 string 物件中,所有指定的 Unicode 字元替換為另一個指定的 Unicode 字元,並返回新的字串。 |
28 | public string Replace( string oldValue, string newValue ) 把當前 string 物件中,所有指定的字串替換為另一個指定的字串,並返回新的字串。 |
29 | public string[] Split( params char[] separator ) 返回一個字串陣列,包含當前的 string 物件中的子字串,子字串是使用指定的 Unicode 字元陣列中的元素進行分隔的。 |
30 | public string[] Split( char[] separator, int count ) 返回一個字串陣列,包含當前的 string 物件中的子字串,子字串是使用指定的 Unicode 字元陣列中的元素進行分隔的。int 引數指定要返回的子字串的最大數目。 |
31 | public bool StartsWith( string value ) 判斷字串範例的開頭是否匹配指定的字串。 |
32 | public char[] ToCharArray() 返回一個帶有當前 string 物件中所有字元的 Unicode 字元陣列。 |
33 | public char[] ToCharArray( int startIndex, int length ) 返回一個帶有當前 string 物件中所有字元的 Unicode 字元陣列,從指定的索引開始,直到指定的長度為止。 |
34 | public string ToLower() 把字串轉換為小寫並返回。 |
35 | public string ToUpper() 把字串轉換為大寫並返回。 |
36 | public string Trim() 移除當前 String 物件中的所有前導空白字元和後置空白字元。 |
上面的方法列表並不詳盡,請存取 MSDN 庫,檢視完整的方法列表和 String 類建構函式。
範例
下面的範例演示了上面提到的一些方法:
比較字串
範例
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
This is test and This is text are not equal.
字串包含字串:
範例
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
The sequence ‘test’ was found.
獲取子字串:
範例
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
Console.ReadKey() ;
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Last night I dreamt of San Pedro
San Pedro
連線字串:
範例
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"};
string str = String.Join("\n", starray);
Console.WriteLine(str);
Console.ReadKey() ;
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Down the way nights are dark
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
在 C# 中,結構體是值型別資料結構。它使得一個單一變數可以儲存各種資料型別的相關資料。struct 關鍵字用於建立結構體。
結構體是用來代表一個記錄。假設您想跟蹤圖書館中書的動態。您可能想跟蹤每本書的以下屬性:
為了定義一個結構體,您必須使用 struct 語句。struct 語句為程式定義了一個帶有多個成員的新的資料型別。
例如,可以按照如下的方式宣告 Book 結構:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
下面的程式演示了結構的用法:
範例
using System;
using System.Text;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1; /* 宣告 Book1,型別為 Books */
Books Book2; /* 宣告 Book2,型別為 Books */
/* book 1 詳述 */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 詳述 */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* 列印 Book1 資訊 */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* 列印 Book2 資訊 */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject :
C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom
Billing Book 2 author : Zara Ali
Book 2 subject : Telecom Billing
Tutorial Book 2 book_id : 6495700
已經用了一個簡單的名為 Books 的結構。在 C# 中的結構與傳統的 C 或 C++ 中的結構不同。C# 中的結構有以下特點:
類和結構有以下幾個基本的不同點:
針對上述討論,讓我們重寫前面的範例:
範例
using System;
using System.Text;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void setValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id =id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1 = new Books(); /* 宣告 Book1,型別為 Books */
Books Book2 = new Books(); /* 宣告 Book2,型別為 Books */
/* book 1 詳述 */
Book1.setValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 詳述 */
Book2.setValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* 列印 Book1 資訊 */
Book1.display();
/* 列印 Book2 資訊 */
Book2.display();
Console.ReadKey();
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
列舉是一組命名整型常數。列舉型別是使用 enum 關鍵字宣告的。
C# 列舉是值型別。換句話說,列舉包含自己的值,且不能繼承或傳遞繼承。
宣告列舉的一般語法:
enum <enum_name>
{
enumeration list
};
其中,
列舉列表中的每個符號代表一個整數值,一個比它前面的符號大的整數值。預設情況下,第一個列舉符號的值是 0.例如:
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
下面的範例演示了列舉變數的用法:
範例
using System;
public class EnumTest
{
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
static void Main()
{
int x = (int)Day.Sun;
int y = (int)Day.Fri;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Fri = {0}", y);
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Sun = 0
Fri = 5
當你定義一個類時,你定義了一個資料型別的藍圖。這實際上並沒有定義任何的資料,但它定義了類的名稱意味著什麼,也就是說,類的物件由什麼組成及在這個物件上可執行什麼操作。物件是類的範例。構成類的方法和變數稱為類的成員。
類的定義是以關鍵字 class 開始,後跟類的名稱。類的主體,包含在一對花括號內。下面是類定義的一般形式:
<access specifier> class class_name
{
// member variables
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
// member methods
<access specifier> <return type> method1(parameter_list)
{
// method body
}
<access specifier> <return type> method2(parameter_list)
{
// method body
}
...
<access specifier> <return type> methodN(parameter_list)
{
// method body
}
}
請注意:
下面的範例說明了目前為止所討論的概念:
範例
using System;
namespace BoxApplication
{
class Box
{
public double length; // 長度
public double breadth; // 寬度
public double height; // 高度
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // 宣告 Box1,型別為 Box
Box Box2 = new Box(); // 宣告 Box2,型別為 Box
double volume = 0.0; // 體積
// Box1 詳述
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// Box2 詳述
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// Box1 的體積
volume = Box1.height * Box1.length * Box1.breadth;
Console.WriteLine("Box1 的體積: {0}", volume);
// Box2 的體積
volume = Box2.height * Box2.length * Box2.breadth;
Console.WriteLine("Box2 的體積: {0}", volume);
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Box1 的體積: 210
Box2 的體積: 1560
類的成員函數是一個在類定義中有它的定義或原型的函數,就像其他變數一樣。作為類的一個成員,它能在類的任何物件上操作,且能存取該物件的類的所有成員。
成員變數是物件的屬性(從設計角度),且它們保持私有來實現封裝。這些變數只能使用公共成員函數來存取。
讓我們使用上面的概念來設定和獲取一個類中不同的類成員的值:
範例
using System;
namespace BoxApplication
{
class Box
{
private double length; // 長度
private double breadth; // 寬度
private double height; // 高度
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
public double getVolume()
{
return length * breadth * height;
}
}
class Boxtester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // 宣告 Box1,型別為 Box
Box Box2 = new Box(); // 宣告 Box2,型別為 Box
double volume; // 體積
// Box1 詳述
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// Box2 詳述
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// Box1 的體積
volume = Box1.getVolume();
Console.WriteLine("Box1 的體積: {0}" ,volume);
// Box2 的體積
volume = Box2.getVolume();
Console.WriteLine("Box2 的體積: {0}", volume);
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
Box1 的體積: 210
Box2 的體積: 1560
類的 建構函式 是類的一個特殊的成員函數,當建立類的新物件時執行。
建構函式的名稱與類的名稱完全相同,它沒有任何返回型別。
下面的範例說明了建構函式的概念:
範例
using System;
namespace LineApplication
{
class Line
{
private double length; // 線條的長度
public Line()
{
Console.WriteLine("物件已建立");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// 設定線條長度
line.setLength(6.0);
Console.WriteLine("線條的長度: {0}", line.getLength());
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
物件已建立
線條的長度: 6
預設的建構函式沒有任何引數。但是如果你需要一個帶有引數的建構函式可以有引數,這種建構函式叫做引數化建構函式。這種技術可以幫助你在建立物件的同時給物件賦初始值,具體請看下面範例:
範例
using System;
namespace LineApplication
{
class Line
{
private double length; // 線條的長度
public Line(double len) // 引數化建構函式
{
Console.WriteLine("物件已建立,length = {0}", len);
length = len;
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line(10.0);
Console.WriteLine("線條的長度: {0}", line.getLength());
// 設定線條長度
line.setLength(6.0);
Console.WriteLine("線條的長度: {0}", line.getLength());
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
物件已建立,length = 10
線條的長度: 10
線條的長度: 6
類的 解構函式 是類的一個特殊的成員函數,當類的物件超出範圍時執行。
解構函式的名稱是在類的名稱前加上一個波浪形(~)作為字首,它不返回值,也不帶任何引數。
解構函式用於在結束程式(比如關閉檔案、釋放記憶體等)之前釋放資源。解構函式不能繼承或過載。
下面的範例說明了解構函式的概念:
範例
using System;
namespace LineApplication
{
class Line
{
private double length; // 線條的長度
public Line() // 建構函式
{
Console.WriteLine("物件已建立");
}
~Line() //解構函式
{
Console.WriteLine("物件已刪除");
}
public void setLength( double len )
{
length = len;
}
public double getLength()
{
return length;
}
static void Main(string[] args)
{
Line line = new Line();
// 設定線條長度
line.setLength(6.0);
Console.WriteLine("線條的長度: {0}", line.getLength());
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
物件已建立
線條的長度: 6
物件已刪除
我們可以使用 static 關鍵字把類成員定義為靜態的。當我們宣告一個類成員為靜態時,意味著無論有多少個類的物件被建立,只會有一個該靜態成員的副本。
關鍵字 static 意味著類中只有一個該成員的範例。靜態變數用於定義常數,因為它們的值可以通過直接呼叫類而不需要建立類的範例來獲取。靜態變數可在成員函數或類的定義外部進行初始化。你也可以在類的定義內部初始化靜態變數。
下面的範例演示了靜態變數的用法:
範例
using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s1 = new StaticVar();
StaticVar s2 = new StaticVar();
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.WriteLine("s1 的變數 num: {0}", s1.getNum());
Console.WriteLine("s2 的變數 num: {0}", s2.getNum());
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
s1 的變數 num: 6
s2 的變數 num: 6
也可以把一個成員函數宣告為 static。這樣的函數只能存取靜態變數。靜態函數在物件被建立之前就已經存在。下面的範例演示了靜態函數的用法:
範例
using System;
namespace StaticVarApplication
{
class StaticVar
{
public static int num;
public void count()
{
num++;
}
public static int getNum()
{
return num;
}
}
class StaticTester
{
static void Main(string[] args)
{
StaticVar s = new StaticVar();
s.count();
s.count();
s.count();
Console.WriteLine("變數 num: {0}", StaticVar.getNum());
Console.ReadKey();
}
}
}
當上面的程式碼被編譯和執行時,它會產生下列結果:
變數 num: 3
本篇文章介紹了C#中一些基礎知識,是接著上一篇部落格寫的
主要介紹了C#中的陣列、字串、結構體、列舉、類
可能有些地方寫的不是很全,大概就是這樣啦。有空會繼續更新
傳送門 |
上
一
篇
\color{00ff90}{上一篇 }
上一篇☀️ 學會程式設計入門必備 C# 最基礎知識介紹(三)——變數、常數、運運算元、判斷、迴圈
下
一
篇
\color{00ff90}{下一篇}
下一篇 ☀️ 學會程式設計入門必備 C# 最基礎知識介紹(五)——方法、封裝、繼承、多型