- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个类只能有如下所示的唯一实例。这使得引用相等性足以等同于对象。
虽然序列化很简单,但反序列化有点棘手,因为不能像我在下面所做的那样分配给 this
。如果仍然只想维护类的唯一实例,我该如何反序列化对象?
public sealed class MyClass :
ISerializable,
IXmlSerializable
{
private static readonly Dictionary<string, MyClass> Cache;
static MyClass() { /* build cache, use private constructor */ }
private MyClass(string name)
{
this.Name = name;
}
public string Name { get; }
public static MyClass Parse(string from)
=> Cache[from];
public void GetObjectData(SerializationInfo info, StreamingContext context)
=> throw new NotImplementedException();
public XmlSchema GetSchema() => null;
public void ReadXml(XmlReader reader)
{
reader.ReadStartElement();
this = Parse(reader.ReadContentAsString());
reader.ReadEndElement();
}
public MyClass(SerializationInfo info, StreamingContext context)
=> this = Parse(info.GetString(nameof(this.Name)));
public void WriteXml(XmlWriter writer)
=> throw new NotImplementedException();
}
最佳答案
一般来说,处理这个问题的方法是,在对象图序列化过程中,使用serialization surrogate mechanism替换单例。 ,其中单例被替换为 Data Transfer Object (DTO)它只包含单例的标识符。然后,稍后,随着图形被反序列化,DTO 最初被反序列化,然后通过查找替换为相应的单例。
例如,如果您的 MyClass
如下所示:
public sealed class MyClass
{
private static readonly Dictionary<string, MyClass> Cache;
static MyClass()
{
Cache = new Dictionary<string, MyClass>()
{
{ "one", new MyClass("one") { OtherRuntimeData = "other runtime data 1" } },
{ "two", new MyClass("two") { OtherRuntimeData = "other runtime data 2" } },
};
}
// XmlSerializer required parameterless constructor.
private MyClass() => throw new NotImplementedException();
private MyClass(string name) => this.Name = name;
public string Name { get; }
public string OtherRuntimeData { get; set; }
public static MyClass Parse(string from) => Cache[from];
public static IEnumerable<MyClass> Instances => Cache.Values;
}
那么只包含 Name
的 DTO 看起来像:
public sealed class MyClassDTO
{
public string Name { get; set; }
public static implicit operator MyClassDTO(MyClass obj) => obj == null ? null : new MyClassDTO { Name = obj.Name };
public static implicit operator MyClass(MyClassDTO dto) => dto == null ? null : MyClass.Parse(dto.Name);
}
注意 implicit operator在 DTO 和原始文件之间进行转换?这将使将代理项注入(inject)序列化图中变得更加容易。
不幸的是,没有标准的方法可以在所有常用的 .Net 序列化程序中实现序列化代理 DTO 的注入(inject)。每个都有自己独立的机制(或根本没有机制)。分解它们:
数据协定序列化程序支持通过 IDataContractSurrogate
替换为代理项界面,如图所示在 this answer至 DataContractJsonSerializer - share an object instance for the whole graph?或 this answer至 How to serialize / deserialize immutable list type in c# .
数据协定序列化程序还支持 IObjectReference
界面如图this answer至 C# DataContract Serialization, how to deserialize to already existing instance .
但不幸的是,XmlSerializer
没有方便地支持通过代理机制注入(inject) DTO。最接近的是来自 this answer 的技巧至 Most elegant XML serialization of Color structure ,这涉及设置 XmlElementAttribute.Type
为引用您的单例类型的每个属性的 DTO 类型,例如如下:
public class RootObject
{
// Technique taken from https://stackoverflow.com/questions/3280362/most-elegant-xml-serialization-of-color-structure
[XmlElement(Type=typeof(MyClassDTO))]
public MyClass MyClass { get; set; }
}
示例 .Net fiddle 在此处展示了这一点:https://dotnetfiddle.net/R07NiW .请注意,这仅适用于我们之前定义的单例及其 DTO 之间的隐式运算符。
当通过 Json.NET 进行序列化时,单例可以用 custom JsonConverter
中的 DTO 替换。 .
protobuf.net支持通过 RuntimeTypeModel.Default.Add(typeof(OriginalType), false) .SetSurrogate(typeof(SurrogateType))
替换代理,如 Can I serialize arbitrary types with protobuf-net? 所示, No serializer defined for type: System.Windows.Media.Media3D.Point3D ,或文章 Protobuf-net: the unofficial manual .
最后,如果您正在使用 BinaryFormatter
(我不推荐使用 here 原因),请使用 SurrogateSelector
Customized Serialization 中所示,支持类似于数据契约(Contract)代理替换机制的机制。 .
SerializationInfo.SetType()
结合 IObjectReference
也受支持,如 this documentation example 所示。 .
关于c# - 如何序列化可能只有唯一实例的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51467120/
这很可能是我的语法错误,因为我对在 C++ 中使用多个文件和结构(特别是将结构传递给函数)还很陌生。这是三个文件: 主要.cpp: #include #include #include #inc
我有 TypeScript NestJS 项目。 我需要验证传入的 DTO 到我的 API。它可以被描述为“创建项目”,其中我们有建筑类型(房屋、公寓、花园),并根据该类型我们需要定义: 房屋:楼层包
是否可以从可用于泛型参数的可能类型集中排除特定类型?如果是如何。 例如 Foo() : where T != bool 将意味着除了类型 bool 之外的任何类型。 编辑 为什么? 以下代码是我尝试强
我的 WebGL 体积光线转换应用程序即将完成。但是我发现了一个问题。我必须通过 2D 纹理模拟 3D 纹理。这不是问题。我正在用小切片创建一个巨大的纹理。巨大纹理的尺寸约为 4096x4096 像素
我正在处理的网页上显示了一个返回顶部按钮。当您向下滚动时,有时单击它时,它会跳到顶部,然后跳回您在页面上的位置,然后像预期的那样平滑滚动到顶部。请记住,它并不总是这样做。这只是一个滞后或故障问题还是我
我对此还很陌生,所以请耐心等待。 我有一个类,它具有三个属性:几个整数和一个用户定义对象的集合。 public class Response { public int num1 { get;
我正在制作一款平台游戏,让玩家每 30 毫秒跳跃一次,并向上添加少量的力。我想我应该使用多线程,因为我之前已经做过一些,而且看起来很简单。无论如何,我尝试了这个: public void jump()
是否可以从可能的类型集中排除特定类型,这些类型可以在泛型参数中使用?如果是这样的话。 例如 Foo() : where T != bool 表示除 bool 类型之外的任何类型。 编辑 为什么? 以下
我正在尝试在单个查询中实现内部和外部联接,我不确定我的做法是正确还是错误,因为我不太擅长查询。 就这样吧。 我有以下表格。 hrs_residentials hrs_residential_utili
关于 my website ,有一段代码可以向页面添加几个元素。这段代码不是我可以编辑的东西,而且我对它放置这些元素的位置不满意,因为它弄乱了我的一些布局。所以我想出了一个小的 jQuery 来将它们
一位客户希望我创建一个数据集,如下所示。我不知道这是否可能或合乎逻辑。 我有表parent: id name ------- ------- 1 parent1 2
这可能吗?google 好像没有这方面的资料.. 这样,如果用户在另一个网站上播放视频或歌曲,我的音量就会自动减小 最佳答案 不,这是不可能的。 如果可能的话,它必须是特定于浏览器的,但我不认为这种情
所以我正在尝试制作响应式页面。问题是为什么它归结为移动数据需要位于列表中。 我会用一些示例代码来解释 所以这可能是桌面上的输出 option1
当您将鼠标悬停在a 元素 上时,是否可以删除url? 这就是我的意思: 最佳答案 一种选择是使用一些 JavaScript。 删除 href=来自 的属性标签,取而代之的是 onclick=...
我已经考虑了几个小时,但我无法取得太大进展。它是这样的: You have an array of size n and q queries. Each query is of the form (l
我一直在尝试编写一个脚本来强化 android。我没有成功! 我正在通过模拟器运行一个 AVD,并且已经用我加载的 android shell 和 bash shell 试过了。正如您将在下面看到的那
Private Sub Workbook_Open() Dim WBname As String WBname = ThisWorkbook.name If Not InStr(WBname, "te
Spark 2.0.0-预览版 我们有一个应用程序使用了相当大的广播变量。我们在大型 EC2 实例上运行它,因此部署处于客户端模式。广播变量是一个巨大的 Map[String, Array[Strin
我正在尝试从此link中提取摘要。但是,我无法仅提取摘要的内容。到目前为止,这是我完成的工作: url <- "http://www.scielo.br/scielo.php?script=sci_a
我的主页中有一个iframe。 iframe页面中有一个modalpopup。因此,当显示modalpopup时,modalpopup的父级是iframe主体和主页父级主体。因此,覆盖层仅覆盖ifra
我是一名优秀的程序员,十分优秀!