c# 设计一个图书管理系统
设计一个简单的图书管理系统,包括以下类:
1、Book 类:表示一本图书,包括图书编号、书名、作者、出版日期等属性。
2、Library 类:表示图书馆,包括一个图书列表,可以添加图书、借出图书、归还图书等操作。
3、Person 类:表示图书馆的读者,包括姓名、借阅的图书列表等属性。
请用 C# 编写上述类,并提供简单的演示代码。
解答:
using System;
using System.Collections.Generic;
class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public DateTime PublicationDate { get; set; }
}
class Library
{
private List<Book> books = new List<Book>();
public void AddBook(Book book)
{
books.Add(book);
Console.WriteLine($"Book '{book.Title}' added to the library.");
}
public void BorrowBook(Book book, Person person)
{
if (books.Contains(book))
{
books.Remove(book);
person.BorrowedBooks.Add(book);
Console.WriteLine($"{person.Name} borrowed the book '{book.Title}'.");
}
else
{
Console.WriteLine($"Sorry, the book '{book.Title}' is not available in the library.");
}
}
public void ReturnBook(Book book, Person person)
{
if (person.BorrowedBooks.Contains(book))
{
person.BorrowedBooks.Remove(book);
books.Add(book);
Console.WriteLine($"{person.Name} returned the book '{book.Title}'.");
}
else
{
Console.WriteLine($"{person.Name} did not borrow the book '{book.Title}'.");
}
}
}
class Person
{
public string Name { get; set; }
public List<Book> BorrowedBooks { get; set; } = new List<Book>();
}
class Program
{
static void Main()
{
Book book1 = new Book { BookId = 1, Title = "Introduction to C#", Author = "John Smith", PublicationDate = new DateTime(2020, 1, 1) };
Book book2 = new Book { BookId = 2, Title = "Data Structures and Algorithms", Author = "Alice Johnson", PublicationDate = new DateTime(2019, 5, 15) };
Library library = new Library();
library.AddBook(book1);
library.AddBook(book2);
Person person1 = new Person { Name = "Alice" };
Person person2 = new Person { Name = "Bob" };
library.BorrowBook(book1, person1);
library.BorrowBook(book2, person2);
library.ReturnBook(book1, person1);
library.ReturnBook(book2, person2);
}
}