当前位置: 首页 > 教程 > C# >

C# this关键字

精华
小牛编辑
204浏览
2023-03-14
在 C# 中,可以使用 this 关键字来表示当前对象,日常开发中我们可以使用 this 关键字来访问类中的成员属性以及函数。不仅如此 this 关键字还有一些其它的用法,下面就通过一些示例来分别演示一下。

1) 使用 this 表示当前类的对象

using System;

namespace www.xnip.cn
{
    class Demo
    {
        static void Main(string[] args) 
        {
            Website site = new Website("小牛知识库","https://www.xnip.cn/");
            site.Display();
        }
    }
    public class Website
    {
        private string name;
        private string url;
        public Website(string n, string u){
            this.name = n;
            this.url = u;
        }
        public void Display(){
            Console.WriteLine(name +" "+ url);
        }
    }
}
运行结果如下:

小牛知识库 https://www.xnip.cn/

2) 使用 this 关键字串联构造函数

using System;

namespace www.xnip.cn
{
    class Demo
    {
        static void Main(string[] args) 
        {
            Test test = new Test("小牛知识库");
        }
    }
    public class Test
    {
        public Test()
        {
            Console.WriteLine("无参构造函数");
        }
        // 这里的 this()代表无参构造函数 Test()
        // 先执行 Test(),后执行 Test(string text)
        public Test(string text) : this()
        {
            Console.WriteLine(text);
            Console.WriteLine("实例构造函数");
        }
    }
}
运行结果如下:

无参构造函数
小牛知识库
实例构造函数

3) 使用 this 关键字作为类的索引器

using System;

namespace www.xnip.cn
{
    class Demo
    {
        static void Main(string[] args) 
        {
            Test a = new Test();
            Console.WriteLine("Temp0:{0}, Temp1:{1}", a[0], a[1]);
            a[0] = 15;
            a[1] = 20;
            Console.WriteLine("Temp0:{0}, Temp1:{1}", a[0], a[1]);
        }
    }
    public class Test
    {
        int Temp0;
        int Temp1;
        public int this[int index]
        {
            get
            {
                return (0 == index) ? Temp0 : Temp1;
            }
    
            set
            {
                if (0==index)
                    Temp0 = value;
                else
                    Temp1 = value;
            }
        }
    }
}
运行结果如下:

Temp0:0, Temp1:0
Temp0:15, Temp1:20

4) 使用 this 关键字作为原始类型的扩展方法

using System;

namespace www.xnip.cn
{
    class Demo
    {
        static void Main(string[] args) 
        {
            string str = "小牛知识库";
            string newstr = str.ExpandString();
            Console.WriteLine(newstr);
        }
    }
    public static class Test
    {
        public static string ExpandString(this string name)
        {
            return name+" https://www.xnip.cn/";
        }
    }
}
运行结果如下:

小牛知识库 https://www.xnip.cn/