C#类(Classes)

来源:互联网 发布:摇滚乐 知乎 编辑:程序博客网 时间:2024/06/05 20:11
类用于定义一个新的引用类型。c#不支持多重继承,但支持一个类多重界面(“interfaces”)。
类的成员包括常量、位域、方法、属性、索引(indexers)、事件、操作符、构造器、析构器和嵌套
类型声明。(一口气说这么多,呼——)
对类中得所有成员有五种访问权限:
·  “public” 可以被所有代码访问;
·  “protected” 只可以被继承类访问;
·  “internal” 只可以被同一个项目的代码访问;
·  “protected internal”只可以被同一个项目的代码或继承类访问;
·  “private” 只可以被本类中的代码访问。
缺省状态是“private”。

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”类中实现。
 
原创粉丝点击