代码改变世界

WCF步步为营(五):数据契约

2008-07-03 17:11  敏捷的水  阅读(787)  评论(0编辑  收藏  举报

1. WCF只能传输序列化的类型,WCF 能自动序列化.net内置的之类型,但是如果需要传输自定义的类型,必须把自定义的类型标注DataContract

image

DataContract标注这个类作为数据契约,DataMember属性指明那些字段公布为原数据,是否必需,顺序是多少。

2. 上面的定义,使得Student可以用在服务契约里,下面的Name可以让客户端的名称和服务端不同。

image

3. 下面是我们生成的代理类,可以看到客户端的名字,而且由于Student的Address未声明DataMember,所以客户端是不可见的

Code
 

 

4. 客户端调用示例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ServiceModel;

using JackWangServiceClient.CalcService;

namespace JackWangServiceClient

{

    class Program

    {

        static void Main(string[] args)

        {

            CalcServiceClient proxy = new CalcServiceClient();

            long result = proxy.AddInt(50, 60);

            Student myStudent = new Student();

            myStudent.FirstName = "Jack";

            myStudent.LastName = "Wang";

            myStudent.Age = 18;

            Student resultStudent = proxy.addAgeOfStudent(myStudent);

            Console.Out.WriteLine("result from server is:" + result);

            Console.Out.WriteLine(resultStudent.FirstName + "," + resultStudent.LastName + "," + resultStudent.Age);

            Console.ReadLine();

        }

    }

}