类和结构的区别

public struct Person //结构实例
{
string Name;
int height;
int weight;

public bool overWeight()
{
//implement something
}
}


public class TestTime // 类实例
{
int hours;
int minutes;
int seconds;

public void passtime()
{
//implementation of behavior
}
}

public class Test //调用过程
{
public static ovid Main
{
Person Myperson=new Person //声明结构
TestTime Mytime=New TestTime //声明类
}
}

结构:结构是值类型,值类型在堆栈上分配地址,所有的基类型都是结构类型。
类:类是引用类型,引用类型在堆上分配地址。
堆栈的执行效率高,可是堆栈的资源有限。不适合处理大复杂的对象。所有结构处理作为基类型对待的小对象。而类处理商业逻辑。虽然结构的初始化也使用了 new 操作符可是结构对象依然分配在堆栈上而不是堆上,如果不使用“新建”(new),那么在初始化所有字段之前,字段将保持未赋值状态,且对象不可用。

结构不能从另外一个结构或者类继承。本身也不能被继承。
类是完全扩展的,不但可以继承其他的类和接口,本身也可以被继承。
虽说结构不能被继承,可是结构能够继承接口,方法和类继承接口一样。
结构实现接口:
interface IImage
{
void Paint();
}

struct Picture : IImage
{
public void Paint()
{
// painting code goes here
}

private int x, y, z;
// other struct members
}

posted @ 2011-11-03 20:44  坏小子小明  阅读(95)  评论(0编辑  收藏  举报