visual C ( )使用列舉和結構建立值型別

2021-10-05 19:37:37 字數 2304 閱讀 3519

9.2 使用結構

用關鍵字enum

enum season;

season colorful=season.fall;

console.

writeline

(colorful)

;

列舉內部的每個元素都關聯乙個整數值。預設第乙個元素對應0,後面每個元素對應的整數都遞增1。

也可以手動將特定整數常量和列舉型別的字面值關聯起來。

enum season..

.;season clolorful=season.fall;

console.

writeline((

int)colorful)

;

多個列舉字面值可具有相同的基礎值。

enum season

列舉的字面值預設是int型別,但可以讓列舉型別基於不同的基礎整型,可以是8種整型中的任何一種:bytesbyteshortushortintuintlongulong

如:enum season:short

如下面**:

using system;

namespace c_8_1

class

program

static

void

main

(string

args)

}}

我們知道類定義的是引用型別,但有時我們只是需要處理少量的資料,這時需要管理堆而造成較多的開銷。更好的做法是將型別定義成結構。結構是值型別,在棧上儲存,這樣能有效減少記憶體管理的 開銷。

結構可包含自己的字段、方法和構造器。構造器與類的構造器是有區別的。

用關鍵字struct開頭

struct time
和類一樣,一般不要在結構中宣告公共字段。可以使用私有字段,為結構新增構造器和方法來初始化和處理這些字段:

struct time

public

inthours()

}

區別如下:

struct time
using system;

namespace c_8_1

struct date

public

override

string

tostring()

";return data;}}

class

program

static

void

main

(string

args)

}}

可將結構變數初始化為另乙個結構變數,前提是哪個結構變數是已經初始化了的。

下面是乙個例子,如果將其中的關鍵字struct換成class又會是另一種結果:

using system;

using system.threading;

namespace c_8_1

struct date

public

override

string

tostring()

";return data;

}public

void

advancemonth()

}}class

program")

; weddinganniversary.

advancemonth()

; console.

writeline

($"new value of weddinganniversary is ");

console.

writeline

($"value of copy is still ");

}static

void

main

(string

args)

}}

使用列舉和結構輸出日期

using system using system.collections.generic using system.linq using system.text namespace structtype defaultdate 實際上,輸出時呼叫了重寫的 tostring 方法 console.w...

使用列舉和結構輸出日期

轉角撞倒豬 原文 使用列舉和結構輸出日期 using system using system.collections.generic using system.linq using system.text namespace structtype defaultdate 實際上,輸出時呼叫了重寫的 ...

結構,聯合和列舉

結構 結構的宣告格式如下 struct id 別忘了右花括號後面的分號 1.和陣列類似的是,結構變數可在定義時初始化,如 struct id tae 同樣的,這種初始化只能在定義時進行。若在定義之後的地方進行,編譯器會報錯 但可用匿名結構進行快速賦值,如 struct id tae tae 錯誤 t...