C# 服务结构可靠集合:序列化问题
可靠的收集(队列)值存储一些复杂类型C# 服务结构可靠集合:序列化问题,c#,serialization,collections,deserialization,azure-service-fabric,C#,Serialization,Collections,Deserialization,Azure Service Fabric,可靠的收集(队列)值存储一些复杂类型SomeUnit // Using reliable collection with a base item type IReliableQueue<BaseClass> myQueue = ...; // Store derived item in the queue SomeUnit myData = ...; // SomeUnit inherit from BaseClass await myQueue.EnqueueAsync(txn,
SomeUnit
// Using reliable collection with a base item type
IReliableQueue<BaseClass> myQueue = ...;
// Store derived item in the queue
SomeUnit myData = ...; // SomeUnit inherit from BaseClass
await myQueue.EnqueueAsync(txn, myData); // OK to store but won't deserialize!
我已经将其标记为[DataContract]
,其成员标记为[DataMember]
,并在其顶部添加了[KnownType(typeof(SomeUnit))]
属性
看起来现在SomeUnit已序列化,但随后引发反序列化异常:
元素“urn:ServiceFabric.Communication:item”包含来自
键入映射到名称的
''. 这个
反序列化程序不知道映射到此名称的任何类型。
如果您正在使用,请考虑使用DATACONTracTracver
DataContractSerializer或将与“SomeUnit”对应的类型添加到
已知类型的列表-例如,通过使用KnownTypeAttribute
属性,或将其添加到传递给
序列化程序
我怎样才能解决它 因为您没有显示任何代码,所以我们只能猜测是什么导致了这种情况 如果使用具有通用项类型的可靠队列,例如
SomeUnit
的基类,则会出现此问题
// Using reliable collection with a base item type
IReliableQueue<BaseClass> myQueue = ...;
// Store derived item in the queue
SomeUnit myData = ...; // SomeUnit inherit from BaseClass
await myQueue.EnqueueAsync(txn, myData); // OK to store but won't deserialize!
无法在接口类型上应用[KnownType]。但是,有一些选项可以支持这一点: 选项1 使用包装合同声明已知类型 选项2 将已知类型指定给 然而,这将需要您 选项3
将配置文件(app.config)中的已知类型指定为。我知道这是一个有点老的主题,但在出现此问题并且不想使用KnownType方法(因为如果有很多派生类型,它可能会变得有点混乱)之后,我能够通过使用以下反射成功地将消息序列化:
[DataContract]
[KnownType("GetKnownTypes")]
public abstract class Event
{
[DataMember]
public DateTime AtTime { get; private set; }
public Event()
{
AtTime = DateTime.Now;
}
private static Type[] GetKnownTypes()
{
return typeof(Event).Assembly.GetTypes()
.Where(x => x.IsSubclassOf(typeof(Event)))
.ToArray();
}
}
你能分享一个重现问题的例子吗?事实上,很难知道这个问题。在序列化与反序列化时,您是否以不同的方式构造了
DataContractSerializer
?反序列化时使用的是不同的类,还是相同的类?@dbc,在这个问题中有Azure服务结构的细节。在本例中,我没有处理DataContractSerializer
本身。创建类型为SomeUnit
的对象的可靠服务。然后尝试排队进入其他可靠服务的可靠队列。这里抛出异常。看起来第二个服务无法反序列化由第一个服务序列化的对象。但这两个服务都引用了包含SomeUnit
的类库。感谢您的关注,我上周无法跟踪。这正是我的情况,除了我试图使用接口而不是基类。但无法使用KnownType
属性标记接口。有什么诀窍可以做到这一点吗?@AsValeO:请查看我最近的编辑,了解如何对接口类型执行此操作的选项。包装器工作得很好!谢谢你完整详细的回答!如果要在应用程序配置中使用泛型类型,此链接非常有用:
[DataContract]
[KnownType("GetKnownTypes")]
public abstract class Event
{
[DataMember]
public DateTime AtTime { get; private set; }
public Event()
{
AtTime = DateTime.Now;
}
private static Type[] GetKnownTypes()
{
return typeof(Event).Assembly.GetTypes()
.Where(x => x.IsSubclassOf(typeof(Event)))
.ToArray();
}
}