• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C#关键字this

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

关键字this有两种基本的用法:
一是用来进行this访问.
二是在声明构造函数时指定需要先执行的构造函数。
 this访问
在类的实例构造函数和实例函数成员中,关键字this表示当前的类实例或者对象的引用。this不能用在静态构造函数和静态函数成员中,也不能在其他地方使用。
当在实例构造函数或方法内使用了与字段名相同的变量名或参数名时,可以使用this来区别字段和变量或者参数。下面的代码演示了this的用法。
public class Dog
{
    public string name;
    public int age;
    public Dog()
    {
    }
    public Dog(string name)       // 在这个函数内,name是指传入的参数name
    {
        this.name = name;           // this.name表示字段name
    }
    public Dog(string name, int age) // 在这个函数内,name是指传入的参数name
    {                     // age是指传入的参数age
        this.name = name;            // this.name表示字段name
        this.age = age;           // this.age表示字段age
    }
}
实际上,this被定义为一个常量,因此,虽然在类的实例构造函数和实例函数成员中,this可以用于引用该函数成员调用所涉及的实例,但是不能对this本身赋值或者改变this的值。比如,this++,--this之类的操作都是非法的。
 
this用于构造函数声明
可以使用如下的形式来声明实例构造函数:
『访问修饰符』【类名】(『形式参数表』) : this(『实际参数表』)
{
   【语句块】
}
其中的this表示该类本身所声明的、形式参数表与『实际参数表』最匹配的另一个实例构造函数这个构造函数会在执行正在声明的构造函数之前执行。
比如:
// ThisAndConstructor.cs
// 关键字this用于声明构造函数
using System;
class A
{
    public A(int n)
    {
        Console.WriteLine("A.A(int n)");
    }
    public A(string s, int n) : this(0)
    {
        Console.WriteLine("A.A(string s, int n)");
    }
}
class Test
{
    static void Main()
    {
        A a = new A("A Class", 1);
    }
}


将输出:
A.A(int n)
A.A(string s, int n)
这说明,执行构造函数A(string s, int n)之前先执行了构造函数A(int n)。


 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
c#冒泡排序发布时间:2022-07-13
下一篇:
Effective C# Item11:优先采用foreach循环语句发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap