static void Main(string[] args) { // 9.定义一个用户类包含 姓名年龄 朋友 等属性 //其中朋友属性是一个列表用来存储多个朋友 //有一个添加朋友的方法 //添加的朋友是一个用户实例 User user = new User() {Name = "桉" ,Age = 18}; User friend = new User() {Name = "意",Age = 17 }; User friend1 = new User() { Name = "昂", Age = 20 }; Console.WriteLine($"用户姓名: {user.Name},年龄: {user.Age}"); user.AddFriend(friend); user.AddFriend(friend1); foreach (var item in user.Friend) { Console.WriteLine($"用户朋友: {item.Name},年龄: {item.Age}"); } } } class User { public string Name { get; set; } public int Age { get; set; } public List<User> Friend { get; set; } = new List<User>(); public void AddFriend(User user) { Friend.Add(user); } }
时间: 2025-09-03 15:14:32 AIGC 浏览: 7
以下是一个简单的 C# 代码示例,实现了一个用户类,包含姓名、年龄和朋友属性,以及添加朋友的方法:
```csharp
using System;
using System.Collections.Generic;
class User
{
public string Name { get; set; }
public int Age { get; set; }
public List<User> Friends { get; set; }
public User(string name, int age)
{
Name = name;
Age = age;
Friends = new List<User>();
}
public void AddFriend(User friend)
{
if (!Friends.Contains(friend))
{
Friends.Add(friend);
// 双向添加朋友关系
if (!friend.Friends.Contains(this))
{
friend.Friends.Add(this);
}
}
}
}
class Program
{
static void Main()
{
User user1 = new User("Alice", 25);
User user2 = new User("Bob", 30);
user1.AddFriend(user2);
Console.WriteLine($"User {user1.Name} has {user1.Friends.Count} friends.");
Console.WriteLine($"User {user2.Name} has {user2.Friends.Count} friends.");
}
}
```
### 代码分析
- **类的设计**:定义了 `User` 类,包含 `Name`、`Age` 和 `Friends` 属性,符合面向对象编程中类封装数据和行为的思想。`Friends` 属性使用 `List<User>` 来存储用户的朋友列表。
- **构造函数**:`User` 类的构造函数用于初始化用户的姓名、年龄和朋友列表。
- **添加朋友方法**:`AddFriend` 方法用于向用户的朋友列表中添加新的朋友,并且确保双向添加朋友关系,即当 `user1` 添加 `user2` 为朋友时,`user2` 也会将 `user1` 作为朋友。
### 优化和改进建议
- **异常处理**:在 `AddFriend` 方法中,可以添加对 `null` 参数的检查,避免传入 `null` 导致异常。
```csharp
public void AddFriend(User friend)
{
if (friend == null)
{
throw new ArgumentNullException(nameof(friend), "Friend cannot be null.");
}
if (!Friends.Contains(friend))
{
Friends.Add(friend);
if (!friend.Friends.Contains(this))
{
friend.Friends.Add(this);
}
}
}
```
- **方法的返回值**:`AddFriend` 方法可以返回一个布尔值,表示是否成功添加了朋友。
```csharp
public bool AddFriend(User friend)
{
if (friend == null)
{
throw new ArgumentNullException(nameof(friend), "Friend cannot be null.");
}
if (!Friends.Contains(friend))
{
Friends.Add(friend);
if (!friend.Friends.Contains(this))
{
friend.Friends.Add(this);
}
return true;
}
return false;
}
```
- **数据验证**:在设置 `Name` 和 `Age` 属性时,可以添加数据验证逻辑,例如年龄不能为负数。
```csharp
private string _name;
public string Name
{
get { return _name; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("Name cannot be null or empty.", nameof(Name));
}
_name = value;
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
if (value < 0)
{
throw new ArgumentException("Age cannot be negative.", nameof(Age));
}
_age = value;
}
}
```
阅读全文