我必须 serialize/deserialize 使用 WCF 的 silverlight 应用程序中的对象吗?

Do I have to serialize/deserialize the object in silverlight application with WCF?

我想在 Silverlight 中创建和使用 WCF 服务。我已经创建了一个服务,该服务 return 来自数据库的这个模型:

namespace SilverlightWithWCFService.Web
{
    [DataContract]
    public class Customer
    {
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string CompanyName { get; set; }
        [DataMember]
        public string ContactName { get; set; }
    }
}

服务如下所示:

namespace SilverlightWithWCFService.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode =  AspNetCompatibilityRequirementsMode.Allowed)]
    public class SampleService
    {

        [OperationContract]
        public List<Customer> CustomerList()
        {
            var custList = new List<Customer>();

            // populate custList

            return custList;
            }
        }
    }
}

在我的 Silverlight 应用程序中,我添加了一个服务引用。此方法调用服务操作:

 public Page()
 {
    InitializeComponent();
    SampleServiceClient client = new SampleServiceClient();
    client.CustomerListCompleted += new EventHandler<CustomerListCompletedEventArgs>(client_CustomerListCompleted);
    client.CustomerListAsync();
 } 

 void client_CustomerListCompleted(object sender, CustomerListCompletedEventArgs e)
 {
     CustomerGrid.ItemsSource = e.Result;
 }

所以我的问题是:我不知道 Silverlight 如何与 WCF 一起工作。我是否必须在 WCF 端序列化某些内容并在客户端反序列化 return 值?如果是这样,缺少什么代码? (在哪里?)

更新:

我认为基于一些在线questions。我应该在完成的事件代码中反序列化 returned e.Result 吗?

Do I have to serialize something on WCF side and deserialize the return value on client side?

不,当您使用网络服务时,底层代码会为您完成所有这些工作。

不要执着于它是 Silverlight。只需将 Silverlight 视为控制台应用程序即可。无论需要在控制台应用程序中做什么来使用 Web 服务,都必须在 Silverlight 中做。唯一的区别是您需要以异步方式处理调用,但这与您的问题所涉及的 web 服务的使用是分开的。


请注意,有一种竞争 技术可以在编译期间完成 Web 服务的所有更新。这就是所谓的 RIA 服务,这是一种完全不同的动物。

我建议您使用 WCF Web 服务,但更新 send/receive 缓冲区的大小将使您在任何真正的数据传输中轻松最大化它们。