代码的魅力

BI, .NET

导航

继承CollectionBase的类的xml序列化

Posted on 2009-03-01 19:40  moge  阅读(388)  评论(0编辑  收藏  举报

看代码:

XML文件
<ArrayOfDepartment>
<Department>
<name>研发中心</name> 
</Department>
<Department>
<name>营销中心</name> 
</Department> 
</ArrayOfDepartment>

[Serializable]
  
public   class   Department
    {
   
public   Department()
    
{
   }
 
   
private   string   _name;
   
public   string   name
    
{
    
get 
      
{
     
return   this ._name;
    }
 
    
set 
      
{
     
this ._name = value;
    }
 
   }
 
 }
 
 
[Serializable]
 
public   class   DepartmentCollection:CollectionBase
   

   
   
public   DepartmentCollection()
    
{
    
// 
    
//   TODO: 在此处添加构造函数逻辑
    
//     
    }
    
   
public   Department  this [ int   index] 
    
{
    
get    return   ((Department)( this .List[index]));} 
   }
 
 
   
public   int   Add(Department dp) 
    
{   
    
return   List.Add(dp) ;
   }
 
 }
 
 
 
public   static   object   Load(Type type,  string   filename)
    
{
    FileStream fs  
=   null ;
    
try 
      
{
     
//   open the stream 
      fs  =   new   FileStream(filename, FileMode.Open,FileAccess.Read);
     XmlSerializer serializer  
=   new   XmlSerializer(type);
     
return   serializer.Deserialize(fs);
    }
 
    
catch (Exception e)
     
{
     
throw   e;
    }
 
    
finally 
      
{
     
if (fs  !=   null )
      fs.Close();
    }