Method returning an object
นิธิ มีแสงเพ็ชร์ 650710559
ตัวอย่างของการใช้ Method returning an object ใน C#
using System;
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
public class Library
{
// ใช้สำหรับสร้างและคืนค่าวัตถุ Book ที่เป็น object
public Book CreateBook(string title, string author)
{
// สร้าง object Book และ return object ไปยังที่เรียกใช้งาน
return new Book(title, author);
}
}
class Program
{
static void Main(string[] args)
{
Library library = new Library();
// เรียกใช้ Method CreateBook ที่จะคืนค่าวัตถุ Book
Book book1 = library.CreateBook("Harry Potter", "J. K. Rowling");
Book book2 = library.CreateBook("Sherlock Holmes", "Sir Arthur Conan Doyle");
// แสดงผลข้อมูลของหนังสือที่ได้จากการเรียก Method ที่คืนค่าเป็นวัตถุ Book
Console.WriteLine($"Title: {book1.Title}, Author: {book1.Author}");
Console.WriteLine($"Title: {book2.Title}, Author: {book2.Author}");
}
}
Output
เปรียบเทียบกับ Java, C, Python
Output
Video
Slide
Reference
Last updated
