C# this关键字介绍

开发 后端
这里介绍C# this关键字,由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有this指针。在静态方法中引用C# this关键字是错误的。

C# this关键字引用类的当前实例。

以下是 this 的常用用途:
◆限定被相似的名称隐藏的成员
◆将对象作为参数传递到其他方法
◆声明索引器

C# this关键字示例:

//this关键字  
//keywords_this.cs  
usingSystem;  
classEmployee  
{  
privatestring_name;  
privateint_age;  
privatestring[]_arr=newstring[5];  
 
publicEmployee(stringname,intage)  
{  
//使用this限定字段,name与age  
this._name=name;  
this._age=age;  
}  
 
publicstringName  
{  
get{returnthis._name;}  
}  
 
publicintAge  
{  
get{returnthis._age;}  
}  
 
//打印雇员资料  
publicvoidPrintEmployee()  
{  
//将Employee对象作为参数传递到DoPrint方法  
Print.DoPrint(this);  
}  
 
//声明索引器  
publicstringthis[intparam]  
{  
get{return_arr[param];}  
set{_arr[param]=value;}  
}  
 
}  
classPrint  
{  
publicstaticvoidDoPrint(Employeee)  
{  
Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);  
}  
}  
 
classTestApp  
{  
staticvoidMain()  
{  
EmployeeE=newEmployee("Hunts",21);  
E[0]="Scott";  
E[1]="Leigh";  
E[4]="Kiwis";  
E.PrintEmployee();  
 
for(inti=0;i<5;i++)  
{  
Console.WriteLine("FriendsName:{0}",E[i]);  
}  
 
Console.ReadLine();  
}  
}  
 
/**//*  
控制台输出:  
Name:Hunts  
Age:21  
FriendsName:Scott  
FriendsName:Leigh  
FriendsName:  
FriendsName:  
FriendsName:Kiwis  
*/ 
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.

由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有this指针。在静态方法中引用C# this关键字是错误的。索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。

【编辑推荐】

  1. 如何用C#和ADO.NET访问
  2. 浅析C# Switch语句
  3. C#验证输入方法详解
  4. 简单介绍C# 匿名方法
  5. C# FileSystemWatcher对象
责任编辑:佚名 来源: 博客园
相关推荐

2009-09-02 09:24:03

C# this关键字

2009-08-06 17:52:23

C#增加that关键字

2009-08-21 14:47:59

C# base关键字

2009-08-13 17:44:34

C# using关键字

2009-08-26 15:16:29

C# lock关键字

2009-08-13 13:04:29

C# lock关键字

2009-08-21 14:16:35

C# New关键字

2011-06-21 09:50:51

volatile

2009-08-13 09:49:16

C#关键字

2009-07-31 16:34:17

dynamicC# 4.0

2009-09-01 15:25:04

C# default关

2024-12-26 00:28:59

C#base​关键字

2024-06-04 17:02:38

newC#编程语言

2025-01-22 08:06:38

C#yield数据迭代

2011-06-14 13:26:27

volatile

2022-01-10 18:11:42

C语言应用技巧

2024-07-09 08:00:48

C#var​关键字

2021-04-18 07:58:22

SQL Server数据库Apply

2023-11-19 22:52:42

2024-05-29 14:09:00

C#编程this
点赞
收藏

51CTO技术栈公众号