(二十八)C#编程基础复习——This关键字

发布时间 2023-11-28 09:50:14作者: 代号六零一

在C#中,可以使用this关键字来表示当前对象,日常开发中我们可以使用this关键字来访问类中的成员属性以及函数。不仅如此this关键字还有一些其他的用法,示例如下:

一、使用this表示当前类的对象

namespace _016
{
    internal class Program
    {
        static void Main(string[] args)
        {          
            Website site = new Website("C语言中文网", "http://c.biancheng.net/");
            site.Display();
            Console.ReadKey();
        }
    }
    public class Website
    {
        private string name;
        private string url;
        public Website(string a,string b)
        {
            this.name = a;
            this.url = b;
        }
        public void Display()
        {
            Console.WriteLine(name+" "+url);
        }
    }
}

运行结果:

二、使用this关键字串联构造函数

namespace _016
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test("C语言中文网");
            Console.ReadKey();
        }
    }
    public class Test
    {
        public Test()
        {
            Console.WriteLine("无参构造函数");
        }
        public Test(string text) : this()
        {
            Console.WriteLine(text);
            Console.WriteLine("实例化构造函数");
        }
    }
}

运行结果:

三、使用this关键字作为类的索引器

 


namespace _016
{
    internal class Program
    {
        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]);
            Console.ReadKey();
        }
    }
    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;
                }
            }
        }
    }
}

运行结果:

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

namespace _016
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string str = "C语言中文网";
            string newstr = str.ExpandString();
            Console.WriteLine(newstr);
            Console.ReadKey();
        }
    }
    public static class Test
    {
        public static string ExpandString(this string name)
        {
            return name + "http://c.biancheng.net/";
        }
    }


}

运行结果: