类型是由字段数据(成员变量)和操作字段数据的成员(属性、方法、构造函数、事件等)所构成的自定义类型。其中字段数据表示类实例(对象)的状态。
public class car
{
//car的字段(状态)
private int _speed;
private string _name;
//car操作字段的属性
public int speed
{
set {this._speed=value;}
get{return this._speed;}
}
public string name
{
set { this._name=value;}
get{return this._name;}
}
//显式定义默认构造函数
public car(){}
//自定义构造函数
public car(string name,int speed)
{
this._name=name;
this._speed=speed;
}
//car的功能(方法)
public void showstate()
{console.writeline("car {0} is going {1} mph", this._name,this. _speed);}
}
public static void main(string[] args)
{
//错误,忘记使用new
car c;
c.name="bruce";
}
public static void main(string[] args)
{
//创建car对象。
car c;//声明了指向尚未创建的car对象的引用。
c=new car("bruce wong",150);//通过new把有效的引用赋给对象,这引用才会指向内存有效的对象。
c.showstate();
console.readkey(true);
}
public car()
{
this._name="my car";
this._speed=100;
}
public car(string name,int speed)
{
this._name=name;
this._speed=speed;
}
class car
{
private string name;
public void setname(string name)
{ this.name=name;}
}
class car
{
public int speed{get;set;}
public string name{get;set;}
public car(){}
public car(int speed)
{
if(speed>150)
{speed=150;}
this.speed=speed;
}
public car(string name)
{
this.name=name;
}
public car(int speed,string name)
{
if(speed>150)
{speed=150;}
this.speed=speed;
this.name=name;
}
}
class car
{
public int speed{get;set;}
public string name{get;set;}
public car(){}
public car(int speed):this(speed,""){}
public car(string name):this(0,name){}
// 主构造函数
public car(int speed,string name)
{
if(speed>150) {speed=150;}
this.speed=speed;
this.name=name;
}
}
class carcollection:ienumerable
{
private arraylist arcar=new arraylist();
public car this[int index]
{
get{ return (car)arcar[index];}
set{arcar.insert(index,value);}
}
//...
}
//错误,writeline是静态成员,是类级别的方法。
console c=new console();
c.writeline("bruce wong");
//正确!writeline是类级别的方法
console.writeline("bruce wong");
static class program
{
static void main(string[] args)
{
//...
}
}