【发布时间】:2013-05-15 12:15:16
【问题描述】:
所以我过去几个小时一直在调查这个问题,很明显我不是唯一一个。为什么我的字典和列表作为数组返回?
我了解出于兼容性考虑,默认使用数组。 WCF 有意识地努力远离 .Net 依赖。但是我的服务器和客户端都是用 C# .Net 开发的,所以我没事。
以下是仅针对 StackOverflow 的类似问题示例:
- WCF service returning array instead of List
- Why does WCF return myObject[] instead of List like I was expecting?
- WCF service returning an array of dictionary
- WCF Proxy Returning Array instead of List EVEN THOUGH Collection Type == Generic.List
- WCF Returning Array instead of List EVEN THOUGH Collection Type == Generic.List
- Why does my WCF service return and ARRAY instead of a List ?
- Array instead of List in WCF Service Proxy Generated using svcutil.exe
我的设置:
我正在通过这个命令生成代理:
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin>svcutil.exe /language:cs
/out:generatedProxy.cs /config:app.config /ct:System.Collections.Generic.List`1
http://192.168.0.99:9000/ProjectDatabase/??
我的服务合同如下所示:
[ServiceContract]
public interface IMyContract
{
[OperationContract]
[ServiceKnownType(typeof(Dictionary<int, string>))]
Dictionary<int, string> getClassDictionary();
}
我的实现:
public Dictionary <int, string> getClassDictionary()
{
Dictionary<int, string> myDict = new Dictionary<int, string>();
myDict.Add(1, "Geometry");
myDict.Add(2, "Algebra");
myDict.Add(3, "Graph Theory");
return myDict;
}
即使在我的Reference.svcmap 我也有:
<CollectionMappings>
<CollectionMapping TypeName="System.Collections.Generic.List`1" Category="List" />
</CollectionMappings>
然而,尽管我尽了最大的努力和研究,我仍然得到:
字典 返回为 ArrayOfKeyValueOfintstringKeyValueOfintstring[]
还有:
List 返回为 T[]
我觉得我已经尝试了所有事情并且做对了所有事情,但我必须遗漏一些东西。那是什么?感谢您的时间、帮助和考虑。
更新:
我什至尝试通过编写serializable struct 并将它们添加到数组中来解决Array 强制执行的方法。
[Serializable]
public struct KeyValuePair<K, V>
{
public K Key { get; set; }
public V Value { get; set; }
}
但是,当我返回 KeyValuePair<int, string>[] 时。我的代理正在生成KeyValuePairOfintstring[] 的返回。
解决方案发布在下方。
【问题讨论】:
-
我喜欢这个
ArrayOfKeyValueOfintstringKeyValueOfintstring[] -
为什么会这样生成代理?
-
奇怪。我刚刚构建了一个返回
Dictionary<int, string>的新服务、主机和客户端,它工作得很好。明天我会写一个新的解决方案,看看是否能解决问题。
标签: c# wcf serialization collections client-server