快讯

初探c#(九)结构(Structs)

2004-02-14 09:34  出处:PConline  作者:依栏望海  责任编辑:pjl 

1.9 结构(Structs)   结构和类又非常多的相似之处,如结构可以实现界面,和可以拥有和类一样的成员。结构与类也有一些重要的区别:结构是值类型,而不是引用类型,所以不支持继承!结构被存在堆栈中或者是内联。结构在精心下可以提高存储效能。例如,定义一个与类有着相同信息的结构可以大大地减少存储空间。在下例中,程序创建并初始化100个points。在类“Point”中需要分配101个独立的对象(object)。*/ class Point { public int x, y; public Point() { x = 0; y = 0; } public Point(int x, int y) { this.x = x; this.y = y; } } class Test { static void Main() { Point[] points = new Point[100]; for (int i = 0; i < 100; i++) points[i] = new Point(i, i*i); } } /* 如果“Point”被作为一个结构,就可以这样啦:*/ struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } /*   因为Point在内联中实例化,所以得到了优化。当然,错误运用的只会适得其反。比如,当我们传递结构的时候就会比传递类要慢。因为结构的传递是拷贝值,类是引用值的地址。数据量越大差距就越明显。   所以“There is no substitute for careful data structure and algorithm design.”(实在是不想译了 ^_^ )。 1.10 界面(Interfaces)   界面用来定义一种程序的契约。有了这个契约,就可以跑开编程语言的限制了(理论上)。而实现界面的 类或者结构要与界面的定义严格一致。界面可以包含以下成员:方法、属性、索引和事件。例子:*/ interface IExample { string this[int index] { get; set; } event EventHandler E; void F(int value); string P { get; set; } } public delegate void EventHandler(object sender, Event e); /*   例子中的界面包含一个索引、一个事件E、一个方法F和一个属性P。   界面可以支持多重继承。就像在下例中,界面“IComboBox”同时从“ITextBox”和“IListBox”继承。 */ interface IControl { void Paint(); } interface ITextBox: IControl { void SetText(string text); } interface IListBox: IControl { void SetItems(string[] items); } interface IComboBox: ITextBox, IListBox {} /*   类和结构可以多重实例化界面。 就像在下例中,类“EditBox”继承了类“Control”,同时从“IDataBound”和“IControl”继承。 */ interface IDataBound { void Bind(Binder b); } public class EditBox: Control, IControl, IDataBound { public void Paint(); public void Bind(Binder b) {...} } /*   在上面的代码中,“Paint”方法从“IControl”界面而来;“Bind”方法从“IDataBound”界面而来,都以“public”的身份在“EditBox”类中实现。
IT热词搜索 来源:360新闻
相关文章

相关软件:

腾讯QQ2012
大小:52.93 MB 授权:免费
腾讯QQ2012
立即下载
腾讯QQ2013
大小:49.32 MB 授权:免费
腾讯QQ2013
立即下载