Appearance
如何控制属性的序列化
通过以下方法可以控制插件的特定属性如果序列化到文件中。活字格中单元格会有两个保存逻辑。
- 在设计器中,保存为 .fgcc 文件。
- 发布会运行时保存为运行时元数据供浏览器中的JavaScript使用。
精细的控制序列化过程可以达成以下目的
- 减小不必要的属性存储,略微提升保存的速度及磁盘占用(特别是某些类型会大量保存在列表中时)
- 避免敏感数据在浏览器中暴露
WARNING
注意,除特别情况下,开发者没必要精细控制属性的序列化。以避免带来不必要的复杂度和Bug
活字格提供了以下方法控制属性的序列化
- DefaultValueAttribute
- 如果属性标注了DefaultValueAttribute当属性值与DefaultValue一致时,这个属性不会保存到文档中, 也不无法在 JavaScript 代码获取属性的值。(这个属性在JavaScript代码中会获取到 undefined)
csharp
using GrapeCity.Forguncy.CellTypes;
using System.ComponentModel;
namespace MyPlugin
{
public class MyPluginCellType : CellType
{
[DefaultValue(10)]
public int MyProperty { get; set; } = 10;
}
}- JsonIgnore
- 如果属性标注了 JsonIgnoreAttribute ,属性值既不会被保存,也不能通过 JavaScript 获取
csharp
using GrapeCity.Forguncy.CellTypes;
using Newtonsoft.Json;
namespace MyPlugin
{
public class MyPluginCellType : CellType
{
[JsonIgnore]
public int MyProperty { get; set; } = 10;
}
}- SaveJsonIgnore
- 如果属性标注了 SaveJsonIgnore ,属性值既不会被保存,但是能通过 JavaScript 代码获取
csharp
using GrapeCity.Forguncy.CellTypes;
using GrapeCity.Forguncy.Plugin;
namespace MyPlugin
{
public class MyPluginCellType : CellType
{
[SaveJsonIgnore]
public int MyProperty { get; set; } = 10;
}
}- PageMetadataJsonIgnore
- 如果属性标注了 PageMetadataJsonIgnore, 属性值会被保存,但是无法通关 JavaScript 代码获取
csharp
using GrapeCity.Forguncy.CellTypes;
using GrapeCity.Forguncy.Plugin;
namespace MyPlugin
{
public class MyPluginCellType : CellType
{
[PageMetadataJsonIgnore]
public int MyProperty { get; set; } = 10;
}
}- ShouldSerializeXXXProperty 方法
- 如果在类中添加了 ShouldSerialize+属性名 方法,对应的属性是否保存和被JavaScript 代码获取,取决于这个方法的返回值,返回 True 则可以被保存或获取,否则则不行。此方法的返回值必须是bool。
实例代码中,如果 MyProperty 值为 10 或 20 时不会被保存。
- 如果在类中添加了 ShouldSerialize+属性名 方法,对应的属性是否保存和被JavaScript 代码获取,取决于这个方法的返回值,返回 True 则可以被保存或获取,否则则不行。此方法的返回值必须是bool。
csharp
using GrapeCity.Forguncy.CellTypes;
namespace MyPlugin
{
public class MyPluginCellType : CellType
{
public int MyProperty { get; set; } = 10;
public bool ShouldSerializeMyProperty()
{
return MyProperty != 10 || MyProperty != 20;
}
}
}更新: 2023-02-27 17:45:10
原文: https://www.yuque.com/robert-bh51n/ea8l6c/yv7tgg89trrur23l