上一篇就结构的性能、局限性以及它和类的比较作了简单的描述,这篇我将接着介绍在使用结构时应该注意和把握的原则:
 通过上篇的介绍,我们可以很自然的意识到结构在效率上的优越性(相对于类),这主要归因于它们在底层的值类型结构。
不过,它们的对于大容量数据和复杂度高的算法进行处理时所表现出来的局限性,使得它的适用范围大受限制。那我们在什么情
况下使用结构才能不受指责和嘲笑呢?
 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键值对于整个系统只用定义
一次,这样使用起来其高效性和方便性都是显而易见的。
,欢迎访问网页设计爱好者web开发。