用C#写一个图书管理系统
时间: 2023-10-03 21:10:21 浏览: 174
好的,下面给出一个简单的图书管理系统的示例代码:
```csharp
using System;
using System.Collections.Generic;
namespace LibraryManagementSystem
{
class Book
{
public string Title { get; set; }
public string Author { get; set; }
public int Year { get; set; }
public bool Available { get; set; }
}
class Library
{
private List<Book> books = new List<Book>();
// 添加图书
public void AddBook(Book book)
{
books.Add(book);
}
// 删除图书
public void RemoveBook(Book book)
{
books.Remove(book);
}
// 展示所有图书
public void ShowAllBooks()
{
Console.WriteLine("所有图书:");
Console.WriteLine("书名\t\t作者\t\t出版年份\t是否可借");
foreach (Book book in books)
{
Console.WriteLine("{0}\t\t{1}\t\t{2}\t\t{3}", book.Title, book.Author, book.Year, book.Available ? "是" : "否");
}
}
// 按书名查找
public void SearchByTitle(string title)
{
Console.WriteLine("搜索结果:");
Console.WriteLine("书名\t\t作者\t\t出版年份\t是否可借");
foreach (Book book in books)
{
if (book.Title == title)
{
Console.WriteLine("{0}\t\t{1}\t\t{2}\t\t{3}", book.Title, book.Author, book.Year, book.Available ? "是" : "否");
}
}
}
// 按作者查找
public void SearchByAuthor(string author)
{
Console.WriteLine("搜索结果:");
Console.WriteLine("书名\t\t作者\t\t出版年份\t是否可借");
foreach (Book book in books)
{
if (book.Author == author)
{
Console.WriteLine("{0}\t\t{1}\t\t{2}\t\t{3}", book.Title, book.Author, book.Year, book.Available ? "是" : "否");
}
}
}
// 借书
public void BorrowBook(string title)
{
foreach (Book book in books)
{
if (book.Title == title && book.Available)
{
book.Available = false;
Console.WriteLine("借阅成功!");
return;
}
}
Console.WriteLine("此书不可借或不存在!");
}
// 还书
public void ReturnBook(string title)
{
foreach (Book book in books)
{
if (book.Title == title && !book.Available)
{
book.Available = true;
Console.WriteLine("还书成功!");
return;
}
}
Console.WriteLine("此书未被借出或不存在!");
}
}
class Program
{
static void Main(string[] args)
{
Library library = new Library();
// 添加几本图书
library.AddBook(new Book { Title = "C#入门经典", Author = "Tom Archer", Year = 2010, Available = true });
library.AddBook(new Book { Title = "Java编程思想", Author = "Bruce Eckel", Year = 2006, Available = false });
library.AddBook(new Book { Title = "Python基础教程", Author = "Magnus Lie Hetland", Year = 2013, Available = true });
library.AddBook(new Book { Title = "C++ Primer Plus", Author = "Stephen Prata", Year = 2011, Available = true });
// 展示所有图书
library.ShowAllBooks();
// 搜索图书
Console.WriteLine("按书名搜索:");
library.SearchByTitle("Java编程思想");
Console.WriteLine("按作者搜索:");
library.SearchByAuthor("Tom Archer");
// 借阅图书
Console.WriteLine("借阅图书:");
library.BorrowBook("Java编程思想");
// 展示所有图书
library.ShowAllBooks();
// 还书
Console.WriteLine("还书:");
library.ReturnBook("Java编程思想");
// 展示所有图书
library.ShowAllBooks();
Console.ReadKey();
}
}
}
```
这个图书管理系统包含了添加、删除、展示、搜索、借阅和还书等功能。用户可以通过命令行界面进行操作。
阅读全文