(转)Web Services使用多态(XmlInclude) ,支持自定义类型
????? 在Web Services方法中,往往使用的都是一個具體類型的參數,這個參數一般就是一個數據對象。ASP.NET Web Services通過聲明XmlIncludeAttribute可以實現Web Services方法中運用多態。
???? XmlIncludeAttribute允許XmlSerializer在序列化火反序列化對象時識別類型。當應用XmlIncludeAttribute時,需指定派生類的Type。XmlSerializer序列化同時包含基類和派生類的對象之后,它就可以識別兩種對象類型。
???? 首先定義基類Vehicle和派生類Car:
1: public abstract class Vehicle 2: { 3: public string LicenseNumber{get;set;} 4: public DateTime MakeTime { get; set; } 5: } 6: ? 7: public class Car : Vehicle 8: { 9: public int DoorNum { get; set; } 10: } 11: ??????? 定義AddVehicle的Web Method,聲明XmlInclude需要添加對命名空間System.Xml.Serialization的引用:
1: [WebMethod] 2: [XmlInclude(typeof(Car))] 3: public void AddVehicle(Vehicle vehicle) 4: { 5: ? 6: } 7: ??????? 查看生成的wsdl,wsdl利用extension的base屬性來描述Car繼承Vechicle。
???????? 查看引用Web Services生成的Reference.cs文件,Vehicle類會有XmlIncludeAttribute的聲明:
1: [System.Xml.Serialization.XmlIncludeAttribute(typeof(Car))] 2: [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.1")] 3: [System.SerializableAttribute()] 4: [System.Diagnostics.DebuggerStepThroughAttribute()] 5: [System.ComponentModel.DesignerCategoryAttribute("code")] 6: [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://tempuri.org/")] 7: public abstract partial class Vehicle : object 8:???????? 客戶端測試代碼:
1: static void Main(string[] args) 2: { 3: localhost.WebService1SoapClient c = new localhost.WebService1SoapClient(); 4: localhost.Car car = new localhost.Car() { 5: LicenseNumber="0001", 6: MakeTime=DateTime.Now, 7: DoorNum=2 8: }; 9: c.AddVehicle(car); 10: } 11: ???????? 在Web Services的AddVehicle方法可以查看傳過來的參數:
??????? Web Services可以支持多態,不過僅僅限制在可以直接引用Web Services的時候有生成可序列化的代碼時能夠使用,要在其他的客戶端使用還是得費一番周折。
source:http://www.cnblogs.com/zhaozhan/archive/2010/10/25/1860867.html
轉載于:https://www.cnblogs.com/zhouchaoyi/articles/1861152.html
總結
以上是生活随笔為你收集整理的(转)Web Services使用多态(XmlInclude) ,支持自定义类型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net网站编码测试
- 下一篇: Entity Framework 实体关