上一篇就結(jié)構(gòu)的性能、局限性以及它和類的比較作了簡單的描述,這篇我將接著介紹在使用結(jié)構(gòu)時應(yīng)該注意和把握的原則:
通過上篇的介紹,我們可以很自然的意識到結(jié)構(gòu)在效率上的優(yōu)越性(相對于類),這主要歸因于它們在底層的值類型結(jié)構(gòu)。
不過,它們的對于大容量數(shù)據(jù)和復(fù)雜度高的算法進(jìn)行處理時所表現(xiàn)出來的局限性,使得它的適用范圍大受限制。那我們在什么情
況下使用結(jié)構(gòu)才能不受指責(zé)和嘲笑呢?
1、如果你正在從事圖像色彩或是固定模式的業(yè)務(wù)處理程序的設(shè)計,或者你在設(shè)計對象群時,需要面對大量結(jié)構(gòu)簡單且狀態(tài)
信息比較少的對象時,我建議你最好選用結(jié)構(gòu)類型來構(gòu)造這些小規(guī)模數(shù)據(jù)體。
2、由于結(jié)構(gòu)的原型是值類型,所以它整個被定義為一個數(shù)據(jù),所以不要試圖在結(jié)構(gòu)里構(gòu)造過多的方法,最好是能不定義方
法,就盡量避免。
我們來看以下微軟提供的一個最具代表性的例子: rgb結(jié)構(gòu)
using system;
/// <summary>
/// rgb結(jié)構(gòu)
/// </summary>
struct rgb
{
public static readonly rgb red = new rgb(255,0,0);
public static readonly rgb green = new rgb(0,255,0);
public static readonly rgb blue = new rgb(0,0,255);
public static readonly rgb white = new rgb(255,255,255);
public static readonly rgb black = new rgb(0,0,0);
public int red;
public int green;
public int blue;
public rgb(int red,int green,int blue)
{
red = red;
green = green;
blue = blue;
}
public override string tostring()
{
return (red.tostring("x2") + green.tostring("x2") + blue.tostring("x2"));
}
}
public class struct
{
static void outputrgbvalue(string color,rgb rgb)
{
console.writeline("the value for {0} is {1}",color,rgb);
}
static void main(string[] args)
{
outputrgbvalue("red",rgb.red);
outputrgbvalue("green",rgb.green);
outputrgbvalue("blue",rgb.blue);
outputrgbvalue("white",rgb.white);
outputrgbvalue("black",rgb.black);
}
}
以上的例子中我們定義了一個結(jié)構(gòu)和靜態(tài)字段,這樣做使我們存儲的效率提高了;使用上又方便了用戶,畢竟記住一個
rgb(255,100,255) 要比記住一個“草淺蘭” 要困難的多;由于靜態(tài)成員的加盟,使得每個rgb鍵值對于整個系統(tǒng)只用定義
一次,這樣使用起來其高效性和方便性都是顯而易見的。
,歡迎訪問網(wǎng)頁設(shè)計愛好者web開發(fā)。