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

Cách định nghĩa cấu trúc (struct) trong C#

Trong C#, struct (cấu trúc) là kiểu dữ liệu giá trị (value type). Nó giúp gom nhóm dữ liệu liên quan của nhiều kiểu khác nhau vào một biến đơn lẻ. Từ khóa struct dùng để tạo cấu trúc.

Cú pháp:

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

Ví dụ hoàn chỉnh

using System;

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; // Khai báo
        Books Book2;
        
        // Gán giá trị Book1
        Book1.title = "Learn AngularJS";
        Book1.author = "David";
        Book1.subject = "AngularJS";
        Book1.book_id = 345;
        
        // Gán giá trị Book2
        Book2.title = "Learn Java in 7 days";
        Book2.author = "Jack";
        Book2.subject = "Java";
        Book2.book_id = 567;
        
        // In thông tin
        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);
        
        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();
    }
}

Kết quả

Book 1 title : Learn AngularJS
Book 1 author : David
Book 1 subject : AngularJS
Book 1 book_id : 345
Book 2 title : Learn Java in 7 days
Book 2 author : Jack
Book 2 subject : Java
Book 2 book_id : 567

Struct vs Class: Struct là value type (lưu trên stack, copy giá trị), không hỗ trợ kế thừa (ke thừa interface được), không có destructor, không thể khai báo constructor không tham số (trước C# 10). Class là reference type (heap), hỗ trợ kế thừa đầy đủ.