如何序列化一个集合以使用 WCF 发送它?
How can I serialize a Collection to send it using WCF?
我正在尝试通过 WCF 发送对象作为此方法中的参数:
[OperationContract]
bool SendProject(Project project);
如果我尝试从客户端调用它,我得到了这个:
There was an error while trying to serialize parameter project. The InnerException message was 'Type 'System.Collections.ObjectModel.Collection`1[[System.Collections.DictionaryEntry, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'
with data contract name 'ArrayOfDictionaryEntry:http://schemas.datacontract.org/2004/07/System.Collections' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example,
by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'.
Please see InnerException for more details.
我搜索了一些信息,我认为错误是我如何序列化“项目”class 中的 class(来自 Dr. WPF 的 class) :
#region ISerializable
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Collection<DictionaryEntry> entries = new Collection<DictionaryEntry>();
foreach (DictionaryEntry entry in _keyedEntryCollection)
entries.Add(entry);
info.AddValue("entries", entries);
}
#endregion ISerializable
问题是我不知道在哪里放置标签“KnownType”或如何正确序列化此词典以使用 WCF 将其作为参数发送。
谢谢!
我有解决方案,不是很干净但是是解决方案。
正如 dbc 所说,将 DictionaryEntry
更新为 KeyValuePair<TKey,TValue>
是推荐的步骤,但解决我的问题的方法是在序列化所在的 class 中设置 [KnownType(typeof(Collection<KeyValuePair<TypeX, TypeY>>))]
。
我正在尝试通过 WCF 发送对象作为此方法中的参数:
[OperationContract]
bool SendProject(Project project);
如果我尝试从客户端调用它,我得到了这个:
There was an error while trying to serialize parameter project. The InnerException message was 'Type 'System.Collections.ObjectModel.Collection`1[[System.Collections.DictionaryEntry, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfDictionaryEntry:http://schemas.datacontract.org/2004/07/System.Collections' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
我搜索了一些信息,我认为错误是我如何序列化“项目”class 中的 class(来自 Dr. WPF 的 class) :
#region ISerializable
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException("info");
}
Collection<DictionaryEntry> entries = new Collection<DictionaryEntry>();
foreach (DictionaryEntry entry in _keyedEntryCollection)
entries.Add(entry);
info.AddValue("entries", entries);
}
#endregion ISerializable
问题是我不知道在哪里放置标签“KnownType”或如何正确序列化此词典以使用 WCF 将其作为参数发送。
谢谢!
我有解决方案,不是很干净但是是解决方案。
正如 dbc 所说,将 DictionaryEntry
更新为 KeyValuePair<TKey,TValue>
是推荐的步骤,但解决我的问题的方法是在序列化所在的 class 中设置 [KnownType(typeof(Collection<KeyValuePair<TypeX, TypeY>>))]
。