C#基础知识之this关键字介绍
作者:Swich 时间:2022-02-08 10:59:16
一、this可以代表引用类的当前实例,包括继承而来的方法,通常可以省略。
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string Name, int Age)
{
this.Age = Age;
this.Name = Name;
}
}
这个不用多说,当对象调用自己内部函数的时候,用到对象使用this即可。
二、this关键字后面跟“:”符号,可以调用其它的构造函数
//声明有实现的构造函数
public Person()
{
this.NAge = 100;
Console.WriteLine("我是超人!");
}
public Person(int nAge)
{
Console.WriteLine("超人的年龄{0}", nAge);
}
//使用this关键字调用了第二个一个参数的构造函数
public Person(int nAge, string strName)
: this(1)
{
Console.WriteLine("我是叫{0}的超人,年龄{1}", strName, nAge);
}
我们创建该对象看看是否调用成功。在Main函数中添加如下代码:
Person p = new Person(10,"强子");
执行会输出:
超人的年龄1
我是叫强子的超人,年龄10
三、声明索引器
索引器类型表示该索引器使用哪一类型的索引来存取数组或集合元素,可以是整数,可以是字符串;this表示操作本对象的数组或集合成员,可以简单把它理解成索引器的名字,因此索引器不能具有用户定义的名称。例如:
public class Person
{
string[] PersonList = new string[10];
public string this[int param]
{
get { return PersonList[param]; }
set { PersonList[param] = value; }
}
}
其中索引的数据类型必须与索引器的索引类型相同。例如:
Person person = new Person();
person[0] = "hello";
person[1] = "world";
Console.WriteLine(person[0]);
看起来对象像个数组一样,呵呵。
标签:C#,this
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SpringBoot消息国际化配置实现过程解析
2023-05-16 01:19:22
![](https://img.aspxhome.com/file/2023/5/67155_0s.png)
从try-with-resources到ThreadLocal,优化你的代码编写方式
2023-11-11 03:19:52
详解springboot中使用异步的常用两种方式及其比较
2021-06-16 17:43:29
![](https://img.aspxhome.com/file/2023/6/63496_0s.jpg)
Spring中Bean的生命周期使用解析
2021-09-06 23:06:54
![](https://img.aspxhome.com/file/2023/4/78924_0s.jpg)
Spring的Aware接口实现及执行顺序详解
2023-03-09 09:50:53
![](https://img.aspxhome.com/file/2023/6/71646_0s.png)
Swing图形界面实现可动态刷新的验证码
2022-03-27 08:08:50
Spring源码解析之编程式事务
2023-06-20 19:17:49
![](https://img.aspxhome.com/file/2023/2/57402_0s.png)
Mybatis-Plus的多数据源你了解吗
2023-07-22 00:46:59
![](https://img.aspxhome.com/file/2023/7/57617_0s.png)
深入理解Java设计模式之备忘录模式
2023-09-20 06:16:43
![](https://img.aspxhome.com/file/2023/3/58433_0s.jpg)
C#对WPF数据绑定的菜单插入Seperator分隔
2022-04-29 17:09:28
JAVA中的Token 基于Token的身份验证实例
2023-11-09 18:05:09
详解Java Selenium中的鼠标控制操作
2023-11-23 14:43:17
idea的spring boot项目实现更改端口号操作
2023-11-23 03:21:17
![](https://img.aspxhome.com/file/2023/5/59355_0s.jpg)
Java(基于Struts2) 分页实现代码
2023-11-04 05:58:58
Java中两个字符串进行大小比较的方法
2023-10-12 13:39:26
Spring Boot实现文件上传下载
2021-11-22 21:19:36
![](https://img.aspxhome.com/file/2023/3/71693_0s.jpg)
C# 创建高精度定时器的示例
2023-03-09 12:35:58
![](https://img.aspxhome.com/file/2023/4/76434_0s.png)
详解C++ STL模拟实现forward_list
2023-06-21 02:36:04
![](https://img.aspxhome.com/file/2023/0/60100_0s.jpg)
spring mvc中的@PathVariable获得请求url中的动态参数
2023-08-22 22:08:40
软件开发七大过程模型
2023-12-22 17:06:14
![](https://img.aspxhome.com/file/2023/2/68722_0s.jpg)