在asp.net中我們通過添加組件類來實現代碼重用 在asp.net項目文件中添加組件類假如為conn.vb 打開這個文件,這個文件是 public class conn end class 這樣我們有兩種方式來進行代碼重用 一種方式為直接在class中寫代碼,一種為在外面定義一個namespaces 如下(1) public class conn inherits system.componentmodel.component dim connstring as string #region " 組件設計器生成的代碼 " public sub new(byval container as system.componentmodel.icontainer) myclass.new() 'windows.forms 類撰寫設計器支持所必需的 container.add(me) end sub public sub new() mybase.new() '該調用是組件設計器所必需的。 initializecomponent() '在 initializecomponent() 調用之后添加任何初始化 end sub '組件重寫 dispose 以清理組件列表。 protected overloads overrides sub dispose(byval disposing as boolean) if disposing then if not (components is nothing) then components.dispose() end if end if mybase.dispose(disposing) end sub '組件設計器所必需的 private components as system.componentmodel.icontainer '注意:以下過程是組件設計器所必需的 '可以使用組件設計器修改此過程。 '不要使用代碼編輯器修改它。 <system.diagnostics.debuggerstepthrough()> private sub initializecomponent() components = new system.componentmodel.container() end sub #end region public function conned() connstring = "user id=sa;password=;initial catalog=huoyun_0405;data source=chenyang;connect timeout=30" conned = connstring end function end class 這是第一種方式我們定義了一個返回數據庫連接字符串的函數conned 這樣我們就可以在其他文件中通過下面的方式來進行代碼重用 dim include as new {asp.net項目名稱}.conn = new {asp.net項目名稱}.conn myconnection.connectionstring = include.conned() 這樣我們就可以定義數據庫連接了 第二種方式就是自定義命名空間 namespace include public class class1 end class public class class2 end class end namespace 好處在于可以包含多個函數,過程,直至變量 其他文件中可以通過 imports {asp.net項目名稱}.include引用 或 imports {asp.net項目名稱}.include.class1進行明確引用