用c#写一个宠物管理系统
时间: 2023-08-02 16:42:18 浏览: 84
好的,下面是一个使用C#写的宠物管理系统的代码示例:
```csharp
using System;
using System.Collections.Generic;
namespace PetManagementSystem
{
// User class
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public List<Pet> Pets { get; set; }
}
// Pet class
public class Pet
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public int Age { get; set; }
}
// Pet management system class
public class PetManagementSystem
{
private List<User> _users;
private int _nextUserId;
private int _nextPetId;
public PetManagementSystem()
{
_users = new List<User>();
_nextUserId = 1;
_nextPetId = 1;
}
// Register a new user
public void Register(string username, string password, string email)
{
User user = new User
{
Id = _nextUserId,
Username = username,
Password = password,
Email = email,
Pets = new List<Pet>()
};
_users.Add(user);
_nextUserId++;
}
// Login with a username and password
public User Login(string username, string password)
{
foreach (User user in _users)
{
if (user.Username == username && user.Password == password)
{
return user;
}
}
return null;
}
// Add a new pet for the specified user
public void AddPet(User user, string name, string type, int age)
{
Pet pet = new Pet
{
Id = _nextPetId,
Name = name,
Type = type,
Age = age,
};
user.Pets.Add(pet);
_nextPetId++;
}
// Get all pets for the specified user
public List<Pet> GetPets(User user)
{
return user.Pets;
}
// Update a pet for the specified user
public void UpdatePet(User user, Pet pet, string name, string type, int age)
{
pet.Name = name;
pet.Type = type;
pet.Age = age;
}
// Delete a pet for the specified user
public void DeletePet(User user, Pet pet)
{
user.Pets.Remove(pet);
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
PetManagementSystem system = new PetManagementSystem();
// Register a new user
system.Register("testuser", "password", "testuser@example.com");
// Login with the registered user
User user = system.Login("testuser", "password");
// Add a new pet for the user
system.AddPet(user, "Fluffy", "Cat", 3);
// Get all pets for the user
List<Pet> pets = system.GetPets(user);
foreach (Pet pet in pets)
{
Console.WriteLine("Name: {0}, Type: {1}, Age: {2}", pet.Name, pet.Type, pet.Age);
}
// Update the pet information
Pet petToUpdate = pets[0];
system.UpdatePet(user, petToUpdate, "Mittens", "Cat", 4);
Console.WriteLine("Updated pet information:");
Console.WriteLine("Name: {0}, Type: {1}, Age: {2}", petToUpdate.Name, petToUpdate.Type, petToUpdate.Age);
// Delete the pet
Pet petToDelete = pets[0];
system.DeletePet(user, petToDelete);
Console.WriteLine("Pet deleted.");
}
}
}
```
以上代码实现了一个简单的宠物管理系统,使用了C#语言,包括了用户注册、登录、添加宠物、查看宠物、修改宠物信息、删除宠物等功能。可以根据实际需求进行修改和扩展。
阅读全文