WizardWu 編程網

一位台灣的工程師,接觸 .NET 逾十年,近年研究 SQL Server、Performance Tuning、手機應用

博客园 首页 新随笔 联系 订阅 管理

dotNET 中的 class (類) 和 VB.NET 的 Module (模組) 為 Reference Type,這種「型別系統」會儲存變數的記憶體位址參考,並在「數據結構」的「堆積 (Heap)」上做配置;其相較於直接把資料存在「數據結構」Stack 中的 Value Type,因為會多做一次記憶體位址參考的動作,會較浪費系統資源。

若您的 .NET 物件只是要存放「數值、字串」等資料,可改用 struct (結構) 這種輕量級的 class。其行為與 class 相似,亦可實作 interface,但不具備如 OOP 的「繼承」等較複雜的功能,亦即它不能有父類或子類。而由於 struct 被設計為 Value Type,因此在效能的表現上會比 class 來得出色。

struct 是從 System.Object 的 System.ValueType 直接繼承而來。與 class 不同的是,struct 雖然也有預設的 constructor,但它不須使用 new 運算子就能執行「個體化」,例如以下的 C# 範例:

MyStruct s;

就等於

MyStruct s = new MyStruct();


由於 Value Type 的 struct 可直接封裝物件的資訊,省略掉了 Reference Type 的物件位址參考步驟,除了可以稍微提升程序的執行效能外,還可節省記憶體的使用。若您的 .NET 程序不需要複雜的 OO 功能,但仍需要物件 instance 使用上的彈性,可考慮改用 struct。而且 VB.NET 和 C# 皆支援 struct (在 VB.NET 中稱為 Structure)。

using
 System;
using
 System.Collections.Generic;
using
 System.Text;
using
 System.Web;
using
 System.Web.Security;
using
 System.Web.UI;
using
 System.Web.UI.WebControls;
using
 System.Web.UI.WebControls.WebParts;
using
 System.Web.UI.HtmlControls;

namespace
 com.公司名稱.Library_Message
{
    
//
class CustomMessage
    
//{ }


    
public struct CustomMessage
    
{
        
public static string popupAlert(Page thisPage, string
 strResourceFileName)
        
{
            Literal litTxtMsg 
= new
 Literal();

            litTxtMsg.Text 
= "<script>alert('" + strResourceFileName + "\\n')</script>"
;

            thisPage.Controls.Add(litTxtMsg);

            
return
 litTxtMsg.Text;

        }
 // end of popupAlert()

代碼 1 用 struct 取代 class 的範例

上方代碼 1 中的 C# 範例,為版工以前寫的,專門用來彈出 JavaScript Alert、Confirm 小視窗的「類別庫 (class library)」專案。由於其不需要 OOP 的「繼承」、override 等功能,因此捨棄用 class,將各個 method 改寫在 struct 中。


-------------------------------------------------
(本文在版工的舊 Blog 中,發表日期為 2006/08/28)

 

posted on 2008-06-28 08:28  WizardWu  阅读(563)  评论(1编辑  收藏  举报