C# 为什么 WCF 返回 myObject[] 而不是我期待的 List<T> ?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/493376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does WCF return myObject[] instead of List<T> like I was expecting?
提问by ScottG
I am returning a List from my WCF method. In my client code, it's return type shows as MyObject[]. I have to either use MyObject[], or IList, or IEnumerable...
我正在从我的 WCF 方法返回一个列表。在我的客户端代码中,它的返回类型显示为 MyObject[]。我必须使用 MyObject[]、IList 或 IEnumerable...
WCFClient myClient = new WCFClient();
MyObject[] list = myClient.GetMyStuff();
or
IList<MyObject> list = myClient.GetMyStuff();
or
IEnumerable<MyObject> list = myClient.GetMyStuff();
All I am doing is taking this collection and binding it to a grid. What is the best object to assign my returned collection?
我所做的就是获取这个集合并将其绑定到网格。分配我返回的集合的最佳对象是什么?
采纳答案by Stever B
You can specify that you want to use a generic list instead of an array by clicking the advanced button when you add a reference, or you can right click on the service reference and choose configure to change it in place.
您可以通过在添加引用时单击高级按钮来指定要使用通用列表而不是数组,或者您可以右键单击服务引用并选择配置以对其进行更改。
The reason is that WCF serializes Generic lists as arrays to send across the wire. The configuration is just telling svcutil to create a proxy that converts them back to a generic list for your convenience.
原因是 WCF 将通用列表序列化为要通过网络发送的数组。配置只是告诉 svcutil 创建一个代理,为了您的方便,将它们转换回通用列表。
回答by Jason Punyon
When you add the service reference to the client project click the advanced button and change collection type from array to what you want it to be...
当您将服务引用添加到客户端项目时,单击高级按钮并将集合类型从数组更改为您想要的...
回答by Andrew Hare
When you use svcutil.exe
to create you client code you need to tell it how to resolve certain references that are not available to it.
当您svcutil.exe
用来创建客户端代码时,您需要告诉它如何解析某些对它不可用的引用。
This is how you would do it for List<T>
:
这是你将如何做到的List<T>
:
svcutil /o:YourService.cs /ct:System.Collections.Generic.List`1 http://example.com/mex
回答by Tad Donaghe
Stever B is correct. WCF tries really hard not to be coupled to .NET. You may want to allow a Java client to connect to your component. Arrays are interoperable. Generic .NET lists aren't.
史蒂文 B 是正确的。WCF 非常努力地不与 .NET 耦合。您可能希望允许 Java 客户端连接到您的组件。数组是可互操作的。通用 .NET 列表不是。
However, you're more than welcome to create your own proxy class that will convert the array back into a List or anything else that you'd like. The nice thing about manually creating your own proxies is that you're in complete control of what they do.
但是,我们非常欢迎您创建自己的代理类,它将数组转换回 List 或您想要的任何其他内容。手动创建您自己的代理的好处是您可以完全控制它们的操作。