DeepSeek教unity------MessagePack-03

数据契约兼容性

你可以使用 [DataContract] 注解代替 [MessagePackObject]。如果类型用 DataContract 进行注解,可以使用 [DataMember] 注解代替 [Key],并使用 [IgnoreDataMember] 代替 [IgnoreMember]

然后,[DataMember(Order = int)] 的行为将与 [Key(int)] 相同,[DataMember(Name = string)][Key(string)] 相同,[DataMember][Key(nameof(member name))] 相同。

在共享库中使用 DataContract 可以使你的类/结构独立于 MessagePack for C# 序列化。然而,这不被分析器或源生成器支持。此外,像 UnionAttributeMessagePackFormatterSerializationConstructor 等功能无法使用。因此,我们建议在可能的情况下使用特定的 MessagePack for C# 注解。

序列化只读/不可变对象成员(SerializationConstructor)

MessagePack for C# 支持只读/不可变对象/成员的序列化。例如,这个结构体可以被序列化和反序列化。

复制代码
/****************************************************
    文件:Test_04.cs
	作者:Edision
    日期:#CreateTime#
	功能:示例4:序列化只读/不可变对象成员
*****************************************************/

using MessagePack;
using UnityEngine;

public class Test_04 : MonoBehaviour
{
    public void Test()
    {
        var data = new Point(99, 9999);
        var bin = MessagePackSerializer.Serialize(data);
        Debug.Log($"【Test_04Logo】{MessagePackSerializer.ConvertToJson(bin)}");
        // 允许反序列化不可变对象。
        var point = MessagePackSerializer.Deserialize<Point>(bin);
        Debug.Log($"【Test_04Logo】{point.X}-{point.Y}");
    }

    [MessagePackObject]
    public struct Point
    {
        [Key(0)]
        public readonly int X;
        [Key(1)]
        public readonly int Y;

        [SerializationConstructor] //注解手动指定要使用的构造函数。
        public Point(int x)
        {
            this.X = x;
            this.Y = -1;
        }

        // 如果没有标记属性,则使用这个(最匹配的参数)。
        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }
    }
}
相关推荐
SmalBox2 小时前
【URP】Shader绘制棋盘格对比内置管线
unity·渲染
EQ-雪梨蛋花汤1 天前
【Unity笔记】Unity 编辑器扩展:打造一个可切换 Config.assets 的顶部菜单插件
unity·编辑器·游戏引擎
SmalBox1 天前
【URP】UnityHLSL顶点片元语义详解
unity·渲染
在路上看风景2 天前
9. Mono项目与Unity的关系
unity
在路上看风景2 天前
1.12 Memory Profiler Package - Summary
unity
SmalBox2 天前
【URP】Unity Shader Tags
unity·渲染
极客柒2 天前
Unity 塔防自用可视化路点寻路编辑器
unity·编辑器·游戏引擎
程序猿多布2 天前
Unity AssetBundle详解
unity·assetbundle
萘柰奈2 天前
Unity学习----【进阶】Addressables(二)--加载资源与打包及更新
学习·unity
lvcoc3 天前
unity 接入火山引擎API,包括即梦AI
windows·unity·ai·火山引擎