TOC

This article is currently in the process of being translated into Thai (~98% done).

Classes:

Static members

ในบทที่แล้วเราได้เรียนเกี่ยวกับ class และ instance object ส่วนใหญ่เราจะสร้าง instance object หลายๆตัวแล้วนำไปใช้ในลักษณะต่างๆกัน แต่บางทีเราก็ต้องการ class ที่ตัวแปรใน class ไม่มีการเปลี่ยนแปลง แล้วเราก็ไม่ต้องสร้าง instance object เราเรียกว่า static member

Class สามารถมี static function และ static field ซึ่งเราไม่สามารถสร้าง instance object ได้ ถ้าเราสร้าง non-static class เราจะไม่สามารถใช้ static member ได้แต่เราสร้าง instance object ได้

นี่คือตัวอย่างของ static class

public static class Rectangle
{
    public static int CalculateArea(int width, int height)
    {
        return width * height;
    }
}

เราจะใช้ keyword static เพื่อที่จะบอกว่า class นี้เป็น static เราจะเรียกชื่อ class Rectangle ก่อนตามด้วยชื่อ method CalculateArea ถ้าไม่เรียก จะ compiler จะประมวลผลไม่ผ่าน

ถ้าจะใช้ method นี้ เราจะเรียกใช้ได้โดยตรงจาก class ดังนี้

Console.WriteLine("The area is: " + Rectangle.CalculateArea(5, 4));

ในตัวอย่างด้านล่าง เราจะมี method ช่วยเพื่อเก็บค่า width และ height จะสังเกตเห็นว่า ทำไมเราถึงไม่เก็บค่าใน class แล้วดึงค่ามาใช้ เพราะว่ามันเป็น static เราสามารถเก็บค่าได้ แต่ได้แค่ 1 version ของ static class

เราสามารถสร้าง non-static class แล้วดึง CalculateArea มาใช้แบบ utility function ได้

public class Rectangle
{
    private int width, height;

    public Rectangle(int width, int height)
    {
        this.width = width;
        this.height = height;
    }

    public void OutputArea()
    {
        Console.WriteLine("Area output: " + Rectangle.CalculateArea(this.width, this.height));
    }

    public static int CalculateArea(int width, int height)
    {
        return width * height;
    }
}

เราได้สร้าง class แบบ non-static และเพิ่ม constructor ที่มี width และ height เป็น parameter และสร้าง instance object และเพิ่ม OutputArea method ทีเป็น static method เพื่อคำนวณพืนที่

การใช้ static โดยทั่วไปแล้ว คือการใช้ class เป็น utility/helper เป็น method ที่จำเป็น แต่ไม่ได้เข้าพวกกับ class อื่นๆ


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!