using System.Text.Json.Serialization;
namespace Dpz.Core.Web.Models;
/// <summary>
/// 接收消息内容
/// </summary>
[Serializable]
public class ReceiveContent
{
/// <summary>
/// 发送人
/// </summary>
[JsonPropertyName("id")]
public required string Id { get; set; }
/// <summary>
/// 发送人头像
/// </summary>
[JsonPropertyName("avatar")]
public string? Avatar { get; set; }
/// <summary>
/// 用户名
/// </summary>
[JsonPropertyName("username")]
public string? Name { get; set; }
/// <summary>
/// 类型
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; set; }
/// <summary>
/// 发送消息内容
/// </summary>
[JsonPropertyName("content")]
public string? Content { get; set; }
/// <summary>
/// 是否我发送的消息
/// </summary>
[JsonPropertyName("mine")]
public bool Mine { get; set; }
/// <summary>
/// 时间戳
/// </summary>
[JsonPropertyName("timestamp")]
public long TimeStamp { get; set; }
/// <summary>
/// 发送人
/// </summary>
[JsonPropertyName("fromid")]
public string? Sender { get; set; }
/// <summary>
/// 接受消息
/// </summary>
/// <param name="user"></param>
/// <param name="message"></param>
/// <returns></returns>
public static ReceiveContent ToReceiveContent(VmUserInfo user, string message)
{
var content = new ReceiveContent
{
Id = user.Id,
Sender = user.Id,
Avatar = user.Avatar,
Content = message,
Mine = false,
Name = user.Name,
TimeStamp = DateTime.Now.ToTimeStamp(),
Type = "friend",
};
return content;
}
public static ReceiveContent ToGroupContent(string groupId, VmUserInfo user, string message)
{
var content = new ReceiveContent
{
Id = groupId,
Sender = user.Id,
Avatar = user.Avatar,
Content = message,
Mine = false,
Name = user.Name,
TimeStamp = DateTime.Now.ToTimeStamp(),
Type = "group",
};
return content;
}
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
这是一个用于处理消息接收的数据模型类,主要用于Web应用中的消息系统。让我详细解释一下这个代码:
类的基本信息
[Serializable]
public class ReceiveContent
ReceiveContent类表示接收到的消息内容[Serializable]特性表明这个类可以被序列化- 使用了
System.Text.Json.Serialization命名空间来支持JSON序列化
属性说明
每个属性都使用了 [JsonPropertyName] 特性来指定JSON序列化时的属性名:
- Id: 消息的唯一标识符(必需字段)
- Avatar: 发送人的头像URL
- Name: 用户名
- Type: 消息类型(如"friend"好友消息、"group"群组消息)
- Content: 消息的具体内容
- Mine: 布尔值,标识是否为当前用户发送的消息
- TimeStamp: 消息的时间戳
- Sender: 发送人的ID
静态工厂方法
1. ToReceiveContent 方法
public static ReceiveContent ToReceiveContent(VmUserInfo user, string message)
- 用于创建好友消息对象
- 接受用户信息和消息内容作为参数
- 自动设置消息类型为"friend"
Mine默认为false(表示是接收到的消息)- 使用当前时间作为时间戳
2. ToGroupContent 方法
public static ReceiveContent ToGroupContent(string groupId, VmUserInfo user, string message)
- 用于创建群组消息对象
- 需要额外的群组ID参数
- 消息类型设置为"group"
- 其他逻辑与好友消息类似
使用场景
这个类主要用于:
- 即时通讯系统:处理好友和群组消息
- API数据传输:通过JSON格式在前后端之间传递消息数据
- 消息历史记录:存储和展示聊天记录
设计特点
- 类型安全:使用了
required关键字确保必要字段不为空 - 灵活性:支持不同类型的消息(好友/群组)
- 可扩展性:通过工厂方法模式便于创建不同类型的消息对象
- JSON兼容:完善的JSON序列化支持,便于前端处理
这是一个设计良好的消息传输模型,适用于现代Web聊天应用的开发。
AI 正在分析代码…
评论加载中...