C#中This的用法

1 第一个this的意思是调用Car( int petals)方法的属性petals。
2 第二个this的意思是实例化Car(String s, int petals)方法中的参数s( this .s = s)。
3 第三个this是调用Car(String s, int petals)方法的两个参数并传参。
4
5 在C#中,this关键字代表当前实例,我们可以用this.来调用当前实例的成员方法,变量,属性,字段等;
6 也可以用this来做为参数状当前实例做为参数传入方法.
7 还可以通过this[]来声明索引器
8
9 下面是你这段程序的注解:
10   using System; // 引入使命空间System
11   namespace CallConstructor // 声明命名空间CallConstructor
12 {
13 public class Car // 声明类Car
14 {
15 int petalCount = 0 ; // 在Car类中声明一个非静态的整型变量petalCount,初始值为0
16 用Static声明的变量叫做静态变量,非静态成员属类的实例,我们只能在调用类的构
17 造函数对类进行实例化后才能通过所得的实例加"."来访问声明一个非静态的字符串变量s,
18 初始值为"null"; 注意:s = "null"与s =
null是不同的
19 String s = " null " ;
20 Car( int petals) // Car类的默认构造函数
21 {
22 petalCount = petals; // Car类的默认构造函数中为 petalCount 赋值为传入的参数petals的值
23 Console.WriteLine( " Constructor w/int arg only,petalCount = " + petalCount); // 输出petalCount
24 }
25 Car(String s, int petals) // 重载Car类的构造函数 Car(String s, int petals)的第二个参数
26 : this (petals) // : this(petals) 表示从当前类中调用petals变量的值来作为构造函数重载方法
27 {
28 this .s = s;
29 Console.WriteLine( " String & int args " );
30 }
31 // 在构造函数中为s赋值
32 // 非静态成员可以在构造函数或非静态方法中使用this.来调用或访问,也可以直接打变量的名字,因此这一句等效于s = s,
33 // 但是这时你会发类的变量s与传入的参数s同名,这里会造成二定义,所以要加个this.表示等号左边的s是当前类自己的变量
34 Car() // 重载构造函数,:
35 : this ( " hi " , 47 ) // this("hi", 47) 表示调Car(String s, int petals) 这个重载的构造函数,并直接传入变量"hi"和47
36 {
37 Console.WriteLine( " default constructor " );
38 }
39 public static void Main()
40 {
41 Car x = new Car();
42 Console.Read();
43 }
44 }
45 }

引自:http://www.cnblogs.com/fangqing1986/archive/2008/05/13/1195302.html 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值