Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cấu trúc và Thành viên của chương trình C#

Cấu trúc (struct) là kiểu giá trị (value type). Giúp một biến giữ dữ liệu liên quan của nhiều kiểu dữ liệu. Từ khóa struct tạo cấu trúc.

Để định nghĩa struct, dùng câu lệnh struct. Định nghĩa kiểu dữ liệu mới với nhiều thành viên.

Ví dụ khai báo cấu trúc Book:

struct Books {
    public string title;
    public string author;
    public string subject;
    public int id;
};

Truy cập và hiển thị thành viên:

Ví dụ

using System;

struct Books {
    public string title;
    public string author;
    public int id;
};

public class testStructure {
    public static void Main(string[] args) {
        Books Book1;
        Book1.title = "PHP IN 7 Days";
        Book1.author = "Jacob Dawson";
        Book1.id = 34;
        Console.WriteLine("Book 1 title: {0}", Book1.title);
        Console.WriteLine("Book 1 author: {0}", Book1.author);
        Console.WriteLine("Book 1 book_id: {0}", Book1.id);
        Console.ReadKey();
    }
}