Object and Collection Initializer
ธันยพร แซ่ลี้ 650710554
What is Object Initializer and Collection Initializer?
หลายคนอาจสงสัยว่า Object and Collection Initializer คืออะไร? บทความนี้เราจะมาไขข้อสงสัยกันค่ะ
Object Initializer in C#
Object Initializer คือวิธีในการกำหนดค่าเริ่มต้นให้กับ fields หรือคุณสมบัติของ class โดยไม่จำเป็นต้องเรียกใช้ constructor มาช่วยในการจัดการ ข้อดีคือ เป็นวิธีการที่ง่ายและสะดวกสบายต่อการใช้งาน
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
class Program
{
static void Main(string[] args)
{
Student std = new Student() { StudentID = 1,
StudentName = "Bill",
Age = 20,
Address = "New York"
};
}
}
Output
Author Name: Ankita Saini
Author Id: 102
Total no of articles: 178
คำอธิบายตัวอย่าง : จากทั้งตัวอย่าง 1.1 , 1.2 และตัวอย่าง 1.3. จะเห็นได้ว่า ทั้ง Class Student Class Geeks และ Class Cat ได้ สร้าง object และกำหนดค่าเริ่มต้นในเวลาเดียวกันโดยใช้เครื่องหมายวงเล็บปีกกาใน main() โดยไม่ใช้ constructor
Collection Initializer in C#
ในทำนองเดียวกันนอกจากเราจะสามารถกำหนดค่าเริ่มต้นให้กับ fields หรือ คุณสมบัติของ class เรายังสามารถกำหนดค่าเริ่มต้นให้กับ collections ได้โดยการใช้ Collection Initializer โดยที่ไม่จำเป็นต้องใช้ method Add() เพื่อเพิ่มองค์ประกอบใน Collection ซึ่ง Collection Initializer สามารถเป็นค่า นิพจน์ หรือตัวเริ่มต้น object ได้ เมื่อมีการเรียกใช้คอมไพเลอร์จะเพิ่มการเรียกโดยอัตโนมัติ
List<Cat> cats = new List<Cat>
{
new Cat{ Name = "Sylvester", Age=8 },
new Cat{ Name = "Whiskers", Age=2 },
new Cat{ Name = "Sasha", Age=14 }
};
คำอธิบายตัวอย่าง : จากตัวอย่างที่ 2.1 และ 2.2 ตัวเริ่มต้นของ object แต่ละรายการจะอยู่ในวงเล็บปีกกาและคั่นด้วยเครื่องหมายจุลภาคและยังสมารถเพิ่ม null เป็นส่วนประกอบได้ นอกจากนี้ยังสามารถระบุองค์ประกอบที่สร้างดัชนีได้ดังตัวอย่างที่ 2.3 หรือเรียกใช้ Item[TKey] เพื่อตั้งค่า ดังตัวอย่างที่ 2.4
เปรียบเทียบ C# กับภาษาอื่นๆ
ภาษา Java
Java ไม่มี "Object Initializer" ที่เหมือนกับ C# แต่เราสามารถกำหนดค่าให้กับฟิลด์ของ object ได้ เช่น การ ใช้ Setter Methods ซึ่งเป็น Method ที่สร้างไว้เพื่อการกำหนดค่าโดยเฉพาะจะไม่มีการคือค่าใดๆ หรือใช้ Instance Initializer Block เพื่อเริ่มต้นสมาชิกข้อมูล Instance ทุกครั้งที่มีการสร้าง object ของ class
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 3.1 : Setter Methods จะใช้พารามิเตอร์ (newName) ที่ได้รับมาในการกำหนดค่าให้กับตัวแปร name โดย this คือส่วนของ keyword ที่ใช้เพื่ออ้างอิง object ปัจจุบัน และในตัวอย่างที่ 3.2 เราได้สร้าง code block กำหนดค่าเริ่มต้นให้ speed = 100 ( speed จะถูก set ค่า โดยอัตโนมัติ )
นอกจากนี้ Java เองก็ไม่มีไวยากรณ์ของ Collection Initializer แต่สามารถใช้วิธีอื่นเข้ามาช่วยได้ เช่น การใช้ Arrays.asList()
package com.tutorialspoint;
import java.util.Arrays;
import java.util.List;
public class ArrayDemo {
public static void main (String args[]) {
// create an array of strings
String a[] = new String[]{"abc","klm","xyz","pqr"};
List<String> list = Arrays.asList(a);
// printing the list
System.out.println("The list is:" + list);
}
}
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 3.3 มีการใช้ asList() ของ Java Arrays เพื่อสร้างและพิมพ์รายการที่สอดคล้องกันใน array string ออกมา
ภาษา Python
Python ไม่มี "Object Initializer" ที่เหมือนกับ C#เราสามารถกำหนดค่าโดยไม่ใช้ constructor ได้โดยการปรับแต่ง method เพื่อเริ่มต้น attributes ได้เอง โดยวิธีการนี้สามารถรับพารามิเตอร์ที่ใช้ในการตั้งค่า attributes ได้
class Car:
def set_values(self, make, model, year):
self.make = make
self.model = model
self.year = year
my_car = Car()
my_car.set_values('Toyota', 'Camry', 2022)
print(my_car.make) # Output: Toyota
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 4.1 เราได้กำหนดให้ set_values() เป็นตัวเริ่มต้น attributes และใช้กำหนดค่าเริ่มต้นให้แก่ attributes ของ object ใน Class car
Python มีการจะกำหนดค่าใน Collection ที่ง่ายและสะดวกจากการกำหนดค่าได้โดยตรง เช่น การใช้ List literal
number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)
Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 4.2 เราสามารถกำหนดค่า ใน list ภานในวงเล็บเหลี่ยม ([]) โดยคั่นข้อมูลแต่ละตัวด้วยเครื่องหมายจุลภาค (,) และสามารถเปลี่ยนแปลงค่าใน list ได้ตลอด
ภาษา C
เนื่องจาก ภาษา C เป็นภาษาแบบ imperative programming (โปรแกรมเชิงคำสั่ง) จึงไม่สนับสนุน OOP เราจึงจะขอยกตัวอย่างเป็นภาษา c++ แทน
ภาษา C++
ไม่มีสิ่งที่เรียกว่า "Object Initializer" เหมือนกันกับ Java แต่ C++ มีวิธีการหลายแบบในการกำหนดค่าให้กับฟิลด์ของ object เช่นการใช้ aggregate initialization
#include <iostream>
struct Person {
std::string name;
int age;
std::string address;
};
int main()
{
// Initialize a Person struct using aggregate
// initialization
Person p1{ "John", 33, "New York" };
// Print out the values of the Person struct
std::cout << "Name: " << p1.name << std::endl;
std::cout << "Age: " << p1.age << std::endl;
std::cout << "Address: " << p1.address << std::endl;
return 0;
}
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 5.1 เป็นตัวอย่างของการใช้ aggregate initialization ในการกำหนดค่าให้กับ struct Person เมื่อมีการสร้าง object
นอกจากนี้ภาษา C++ สามารถกำหนดค่าให้ Collection ได้ โดยใช้ initializer list
#include<iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int i = 0, int j = 0):x(i), y(j) {}
/* The above use of Initializer list is optional as the
constructor can also be written as:
Point(int i = 0, int j = 0) {
x = i;
y = j;
}
*/
int getX() const {return x;}
int getY() const {return y;}
};
int main() {
Point t1(11, 17);
cout<<"x = "<<t1.getX()<<", ";
cout<<"y = "<<t1.getY();
return 0;
}
Output
x = 11, y = 17
คำอธิบายตัวอย่าง : ในตัวอย่างที่ 5.2 มีการใช้ initializer list เพื่อระบุรายการตัวเริ่มต้นให้กับ collection โดยใช้ {}
ตอนที่สร้าง object ซึ่งมีความคล้ายคลึงกับ c#
video
Reference
Object Initializer (C#) : Mahesh Chand. (2023).sharpcorner.com.https://www.c-sharpcorner.com/UploadFile/mahesh/object-initializer-in-C-Sharp/
Example 1.1 : TutorialsTeacher. (2024). tutorialsteacher.com. https://www.tutorialsteacher.com/csharp/csharp-object-initializer.
Example 1.2 : ankita_saini. (2021). geeksforgeeks.org.https://www.geeksforgeeks.org/object-and-collection-initializer-in-c-sharp/
Example 1.3 : BillWagner (2024) Object and Collection Initializers - C#. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers.
Collection Initializer (C#) and Example 2.1, 2.3, 2.4 : BillWagner (2024b) Object and Collection Initializers - C#. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers.
Example 2.2 : GeeksforGeeks (2021) Object and Collection Initializer in C#. https://www.geeksforgeeks.org/object-and-collection-initializer-in-c-sharp/.
Object Initializer (Java) and Example 3.1 : W3Schools.com (no date). https://www.w3schools.com/java/java_encapsulation.asp.
Example 3.2 : Instance Initializer block in Java - javatpoint (no date). https://www.javatpoint.com/instance-initializer-block.
Collection Initializer (Java) and Example 3.3 : Java Arrays asList() method (no date). https://www.tutorialspoint.com/java/util/arrays_aslist.htm.
Object Initializer (Python) and Example 4.1 : Sumich, A. and Melnikov, E. (2024) Class constructors. https://diveintopython.org/learn/classes/object-instantiation.
Collection Initializer (Python) and Example 4.2 : GeeksforGeeks (2024) Literals in Python. https://www.geeksforgeeks.org/literals-in-python/.
C : บทเรียนภาษา C, สอนภาษา C เบื้องต้น - MarcusCode (no date). https://marcuscode.com/lang/c#google_vignette.
Object Initializer (C++) and Example 5.1 : GeeksforGeeks (2023) Aggregate Initialization in C++ 20. https://www.geeksforgeeks.org/aggregate-initialization-in-cpp-20/.
Collection Initializer (C++) and Example 5.2 : C++ Initializer List - javatpoint (no date). https://www.javatpoint.com/cpp-initializer-list.
Constructor : GeeksforGeeks (2020) C# | Constructors. https://www.geeksforgeeks.org/c-sharp-constructors/.
Item[TKey] : Dotnet-Bot (no date b) Dictionary.Item[TKey] Property (System.Collections.Generic). https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.item?view=net-8.0#system-collections-generic-dictionary-2-item(-0).
Last updated