1. 程式人生 > 實用技巧 >c# struct的使用

c# struct的使用

為結構定義預設(無引數)建構函式是錯誤的。 在結構體中初始化例項欄位也是錯誤的。 只能通過兩種方式初始化結構成員:一是使用引數化建構函式,二是在宣告結構後分別訪問成員。 對於任何私有成員或以其他方式設定為不可訪問的成員,只能在建構函式中進行初始化。

如果使用 new 運算子建立結構物件,則會建立該結構物件,並呼叫適當的建構函式。 與類不同,結構的例項化可以不使用 new 運算子。 在此情況下不存在建構函式呼叫,因而可以提高分配效率。 但是,在初始化所有欄位之前,欄位將保持未賦值狀態且物件不可用。

示例如下:

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) {
// 初始化: TestStruct testStruct1 = new TestStruct();//方式1 TestStruct testStruct2 = new TestStruct(10, 10);//方式2 // 顯示結果: Console.Write("testStruct 1: "); Console.WriteLine("x = {0}, y = {1}", testStruct1.x, testStruct1.y); Console.Write(
"testStruct 2: "); Console.WriteLine("x = {0}, y = {1}", testStruct2.x, testStruct2.y); // 在不使用 new 運算子的情況下建立 testStruct 物件: TestStruct testStruct3; testStruct3.x = 11; testStruct3.y = 12; Console.Write("testStruct 3: "); Console.WriteLine("x = {0}, y = {1}", testStruct2.x, testStruct2.y); // 控制檯保持開啟. Console.WriteLine("任意鍵繼續."); Console.ReadKey(); /* 輸出: testStruct 1: x = 0, y = 0 testStruct 2: x = 10, y = 10 testStruct 3: x = 11, y = 12 */ Console.ReadLine(); } } public struct TestStruct { //public int z = 10;//錯誤 在結構體中初始化例項欄位是錯誤的 public int x, y; public TestStruct(int p1, int p2) { x = p1; y = p2; } } }