日期:2013-03-09  浏览次数:20532 次

上一篇就结构的性能、局限性以及它和类的比较作了简单的描述,这篇我将接着介绍在使用结构时应该注意和把握的原则:
通过上篇的介绍,我们可以很自然的意识到结构在效率上的优越性(相对于类),这主要归因于它们在底层的值类型结构。
不过,它们的对于大容量数据和复杂度高的算法进行处理时所表现出来的局限性,使得它的适用范围大受限制。那我们在什么情
况下使用结构才能不受指责和嘲笑呢?
1、如果你正在从事图像色彩或是固定模式的业务处理程序的设计,或者你在设计对象群时,需要面对大量结构简单且状态
信息比较少的对象时,我建议你最好选用结构类型来构造这些小规模数据体。
2、由于结构的原型是值类型,所以它整个被定义为一个数据,所以不要试图在结构里构造过多的方法,最好是能不定义方
法,就尽量避免。

我们来看以下微软提供的一个最具代表性的例子: RGB结构
using System;

/// <summary>
/// RGB结构
/// </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);
}
}
以上的例子中我们定义了一个结构和静态字段,这样做使我们存储的效率提高了;使用上又方便了用户,毕竟记住一个
RGB(255,100,255) 要比记住一个“草浅兰” 要困难的多;由于静态成员的加盟,使得每个RGB键值对于整个系统只用定义
一次,这样使用起来其高效性和方便性都是显而易见的。