如果你要写一个返回一个称为GetPerson的PersonCollection的实例的Web方法(参列表4),SPROXY将仅生成一个代理类Person,而且返回类型变为Person()。
列表 4: 返回一个PersonCollection实例的WebMethod:
[WebMethod]
public PersonCollection GetPeople() { return PersonCollection.CreateNew(); } | 如果列表4是你提供给消费者的全部, 那么,虽然他们的代码编译成功,但是当从Web方法返回的Person数组被初始化时,可怜的消费者将会遇到一个运行时刻错误抛出SoapException 。最后,因为你定义了其他一些派生于Person的类,所以你也应该设法使你的Web服务消费者能够使用这些类型。
既然你已经了解了问题的一切, 修改就很容易了。使用在 System.Xml.Serialization中定义的 XmlInclude属性来指定另外一些类型――消费者方也需要为它们生成代理类 。在类自身的首部加上XmlInclude属性,用类型对象初始化它――这些类型对象用于每一个需要代理的额外类型。列表5 展示了Web服务的类的首部(该类包含了GetPeople方法)定义情况:
列表5: 通过使用XmlInclude属性来确保子类型在Web服务的消费者端已经定义
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.Services; using BusinessCollections; using System.Xml.Serialization;
namespace Service { /// <summary> /// Summary description for Service1. /// </summary>
[XmlInclude(typeof(Customer)),
XmlInclude(typeof(Person)), XmlInclude(typeof(Employee))] public class Service1 : System.Web.Services.WebService { public Service1() { //CODEGEN: This call is required by the ASP.NET Web服务 //Designer InitializeComponent(); }
[Component Designer generated code] // WEB SERVICE EXAMPLE // The HelloWorld() example service returns the string // Hello World // To build, uncomment the following lines then save and build // the project // To test this web service, press F5
[WebMethod()]
public PersonCollection GetPeople() { return PersonCollection.CreateNew(); } } } | 为了测试网络服务和网络方法,可以产生一个控制台程序。 选择“ Project”-“Add Web Reference”,然后添加上面的网络服务。 声明一个Person()的实例,然后激活Web方法即可。
五、小结
本文介绍了结合XML Web服务环境的多态性问题。你可从中了解到,代理类型不包含方法,且不必为Web服务消费者产生子类型――如果你不小心很容易破坏继承关系。
如果在你的Web方法中包括子类型参数,SPROXY将会为消费者产生那些类型。否则,XmlInclude属性将指示XML Web服务工具生成额外类型。
|
|