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

在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/";
        }
    }


}

运行结果:

posted @   代号六零一  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示