this关键字之一个有趣的用法
2024-08-21 21:04:45
this关键字
1.首先一个用处就是代表当前类的对象。
2.当我们对构造函数进行重载的时候代码如下:
public class Class1 { public string Name { get; set; } public int Age { get; set; } public string Grade { get; set; } public int English { get; set; } public int Math { get; set; } public int Chinese { get; set; } public Class1(string name,int age,string grade,int english,int math,int chinese) { this.Name = name; this.Age = age; this.Grade = grade; this.English = english; this.Math = math; this.Chinese = chinese; } public Class1(string name,int english, int math, int chinese) { this.Name = name; this.English = english; this.Math = math; this.Chinese = chinese; } public Class1(string name, int age) { this.Name = name; this.Age = age; } public Class1() { } }
以上代码完全没有问题,但是不免有些代码冗余的现象。我们可以使用this关键字
public class Class1 { public string Name { get; set; } public int Age { get; set; } public string Grade { get; set; } public int English { get; set; } public int Math { get; set; } public int Chinese { get; set; } public Class1(string name,int age,string grade,int english,int math,int chinese) { this.Name = name; this.Age = age; this.Grade = grade; this.English = english; this.Math = math; this.Chinese = chinese; } public Class1(string name,int english, int math, int chinese):this(name,0,"c",english,math,chinese) { //this.Name = name; //this.English = english; //this.Math = math; //this.Chinese = chinese; } public Class1(string name, int age) { this.Name = name; this.Age = age; } public Class1() { } }
即this的第二个用处为在类中显式的调用本类的构造函数
最新文章
- 简述linux同步与异步、阻塞与非阻塞概念以及五种IO模型
- SQL语法
- 【转】不容忽视的ClassNotFoundException
- 【12-JDBC编程】
- centos7安装mplayer 错误集锦
- web前端工程师校园招聘要求
- spring-data-elasticsearch整合elasticsearch
- C语言接口的写法(以toyls命令为例)
- AFNetworking源码分析
- 3TB硬盘的容量已经超出了传统分区标准的支持
- Web Api中实现Http方法(Put,Post,Delete)
- 用php和imagemagick来处理图片文件的上传和缩放处理
- UVa 495 - Fibonacci Freeze
- 萌新的IDEA_web开发笔记(未完)
- C# Winform开发以及控件开发的需要注意的,被人问怕了,都是基础常识
- 今天开始学习模式识别与机器学习Pattern Recognition and Machine Learning (PRML),章节5.1,Neural Networks神经网络-前向网络。
- (转载)基于Unity~UGUI的简单UI框架(附UIFramework源码)
- html5-Input类型
- Spring Boot和Dubbo整合
- 每日英语:Got a Case of the Mondays? Blame the Sunday Blues