反序列化

来源:互联网 发布:sqlserver 排序 编辑:程序博客网 时间:2024/04/28 03:00

反序列化就是读取xml文件并将其值自动匹配给类中的公有属性或方法或字段,也就是上面的逆操作。 C#复制代码
webinfo info = new webinfo();    

//用webinfo这个类造一个XmlSerializer    
XmlSerializer ser = new XmlSerializer(typeof(webinfo));    

string path = Server.MapPath("webinfo.xml");    

//Stream用于提供字节序列的一般视图,这里将打开一个xml文件    
Stream file = new FileStream(path, FileMode.Open, FileAccess.Read);    

//把字节序列(stream)反序列化   
info = (webinfo)ser.Deserialize(file);    

Response.Write("站长:" + info.userName + "<br>");    
Response.Write("站名:" + info.webName + "<br>");    
Response.Write("域名:" + info.webUrl);   

输出结果:


为了更好的封装和保护类的成员和方法,我们将类webinfo改写成: 折叠展开C#复制代码
public class webinfo    
{    
    //站长    
    private string userName;    
    public string UserName    
    {    
        get   
        {    
            return userName;    
        }    
        set   
        {    
            userName = value;    
        }    
    }    

    //站名    
    private string webName;    
    public string WebName    
    {    
        get   
        {    
            return webName;    
        }    
        set   
        {    
            webName = value;    
        }    
    }    

    //域名    
    private string webUrl;    
    public string WebUrl    
    {    
        get   
        {    
            return webUrl;    
        }    
        set   
        {    
            webUrl = value;    
        }    
    }    
}   
使用时区别仅仅是小小的改动具体的可以看下面: C#复制代码
webinfo info = new webinfo();        
info.userName = "脚本之家";-->info.UserName = "脚本之家";    
info.webName = "脚本"; -->info.WebName  = "脚本";       
info.webUrl = "http://www.jb51.net";  -->//自己写吧   反序列化就是读取xml文件并将其值自动匹配给类中的公有属性或方法或字段,也就是上面的逆操作。 C#复制代码
webinfo info = new webinfo();

//用webinfo这个类造一个XmlSerializer
XmlSerializer ser = new XmlSerializer(typeof(webinfo));

string path = Server.MapPath("webinfo.xml");

//Stream用于提供字节序列的一般视图,这里将打开一个xml文件
Stream file = new FileStream(path, FileMode.Open, FileAccess.Read);

//把字节序列(stream)反序列化
info = (webinfo)ser.Deserialize(file);

Response.Write("站长:" + info.userName + "<br>");
Response.Write("站名:" + info.webName + "<br>");
Response.Write("域名:" + info.webUrl);

输出结果:


为了更好的封装和保护类的成员和方法,我们将类webinfo改写成: 折叠展开C#复制代码
public class webinfo
{
//站长
private string userName;
public string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}

//站名
private string webName;
public string WebName
{
get
{
return webName;
}
set
{
webName = value;
}
}

//域名
private string webUrl;
public string WebUrl
{
get
{
return webUrl;
}
set
{
webUrl = value;
}
}
}
使用时区别仅仅是小小的改动具体的可以看下面: C#复制代码
webinfo info = new webinfo();
info.userName = "脚本之家";-->info.UserName = "脚本之家";
info.webName = "脚本"; -->info.WebName = "脚本";
info.webUrl = "http://www.jb51.net"; -->//自己写吧
0 0
原创粉丝点击