Asp.net 为什么在web服务中需要序列化

Asp.net 为什么在web服务中需要序列化,asp.net,web-services,xml-serialization,Asp.net,Web Services,Xml Serialization,我有一个Web服务: public class Product { public int ProductId { get; set; } public string ProductName { get; set; } } public class Service : System.Web.Services.WebService { public Service () { //Uncomment the following line if using d

我有一个Web服务:

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
}


public class Service : System.Web.Services.WebService
{
    public Service () {
        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public List<Product> GetItems()
    {
        List<Product> productList = new List<Product>()
        {
            new Product{ProductId=1,ProductName="Pencil"},
            new Product{ProductId=2,ProductName="Pen"}
        };

        return productList;
    }
公共类产品
{
public int ProductId{get;set;}
公共字符串ProductName{get;set;}
}
公共类服务:System.Web.Services.WebService
{
公共服务(){
//如果使用设计的组件,请取消注释以下行
//初始化组件();
}
[网络方法]
公共列表GetItems()
{
List productList=新列表()
{
新产品{ProductId=1,ProductName=“Pencil”},
新产品{ProductId=2,ProductName=“Pen”}
};
返回产品列表;
}
在asp.net应用程序中,我会像这样使用它:

     localhost.Service s = new localhost.Service();
    List<localhost.Product> k = new List<localhost.Product>();
    k = s.GetItems().ToList();  // i am getting the values here.
localhost.Service s=new localhost.Service();
列表k=新列表();
k=s.GetItems().ToList();//我在这里获取值。

现在我的问题是,当我返回自定义类型时,我是否需要序列化我的webmethod?我们应该什么时候序列化?是否有必要,如果有,那么条件是什么?

否,您不必这样做。执行引擎会注意到您返回自定义类型并将其正确序列化为SOAP(!=XML)


PS:考虑到WCF

是的,我也在学习WCF。所以,当我们需要序列化的时候,可以解释一下。@ Cyrd2010:在Web服务/WCF不需要的情况下,引擎为我们做了。当我们想以某种自定义的方式存储或传输对象时,需要进行序列化。例如,如果我们想将对象保存到文件。你在说ASP.net吗engine@Cloud2010:是的,关于它。在WCF的情况下,您必须使用
DataContracts
它更明确,但实际的序列化仍然是由WCF引擎完成的。