C# this的五种用法

https://blog.csdn.net/qq_38693757/article/details/126305183

一、需求
一般来说,this 仅仅局限于对象内部,对象外部是无法看到的,这就是this的基本思想,在我们的项目开发中,this关键字用的并不多,这也导致有些程序员对它的认识就不充足,有些知识点就会错过,this的功能绝对不是网上一些课程讲的那样,只是用来区分全局变量和局部变量,下面我就介绍 this 的几种用法,必定能让你对这个关键字有一个全新的认识。

二、区分当前类的对象
这个是常用的功能,如下图,熟悉的可以直接跳过,假设当前类有一个全局变量和当前方法中的参数名一模一样的时候,Visual Studio 就会提示异常,因为系统不知道你到底要给谁赋值,按 C# 的编程规范来说,全局变量最好第一个字母用大写,当然你也可以用小写,在遇到下面的这种情况时,只要前面加一个 this,系统就知道左边的 name 是当前类的成员,而右边的 name 则是方法的参数。

   

这时的 this 我们看到是一个正常的蓝色,如果不需要用到 this 关键字,那么 this 字体则是灰色的。

 

三、作为参数传递

如果其他类的参数类型和当前类一致,直接写 this 即可

    public class Test1
    {
        public void MyTest(Test2 test2)
        {
            Console.WriteLine(test2.Name);
        }
    }
 
    public class Test2
    {
        public string Name = "厚礼蟹";
        public void MyTest()
        {
            new Test1().MyTest(this);
        }
    }

调用 Test2.MyTest() 就会输出:厚礼蟹

四、作为索引器
作为索引器,在平时的项目中用的并不多,但在微软给我们封装好的方法中,用的特别多,我们常用的数组,List 等,基本都是使用索引器去读取的。

namespace 计算3
{
    public class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1();
            Console.WriteLine(test1[1]);
 
            Console.ReadKey();
        }
    }
 
    public class Test1
    {
        string[] NameList = new string[3] { "张三", "李四", "王五" };
        public string this[int index]
        {
            get
            {
                if(index < 0 || index >= NameList.Length)
                {
                    Console.WriteLine("index 的值超过了数组的范围");
                    return null;
                }
                return NameList[index];
            }
        }
    }
}

  执行后,会输出:李四

五、调用其他的构造函数

在实例化当前的类的时候,不仅仅是调用一个构造函数,用 this 就可以调用其他的构造函数,甚至在调用的时候,还可以执行其他的属性,字段,调用其他的方法,这些都是没问题的。

namespace 计算3
{
    public class Program
    {
        static void Main(string[] args)
        {
            Test1 test1 = new Test1("王五");
           
            Console.ReadKey();
        }
    }
 
    public class Test1
    {
        public static int GetAge
        {
            get => 4;
        }
 
        public Test1()
        {
        }
 
        public Test1(string name, int age)
        {
            Console.WriteLine("姓名:" + name);
            Console.WriteLine("年龄:" + age);
        }
 
        public Test1(string name) : this(name, GetAge)
        {
        }
    }
}

  

可以看到,这里的写法和 base 关键字类似,不过 base 是调用父类的构造函数。

执行后输出:

姓名:王五
年龄:4

 下面这个例子更明显,原文链接:https://blog.csdn.net/qiaodahua/article/details/134604440

namespace ConsoleApp1
{
    public class Test
    {
        public Test()
        {
            Console.WriteLine("no parameter");
        }
        public Test(string str) : this()
        {
            Console.WriteLine("one parameter: " + str);
        }
 
        public Test(string str1, string str2): this(str1)
        {
            Console.WriteLine("two parameters: " + str1 + " ; " + str2);
        }
    }
 
    public class ProgramTest
        {
        static void Main(string[] args)
        {
            Console.WriteLine("Test t1 = new Test();");
            Test t1 = new Test();
            Console.WriteLine("Test t2 = new Test('str1');");
            Test t2 = new Test("str1");
            Console.WriteLine("Test t3 = new Test('str2', 'str3');");
            Test t3 = new Test("str2", "str3");
        }
        }
}

  结果:

Test t1 = new Test();
no parameter
Test t2 = new Test('str1');
no parameter
one parameter: str1
Test t3 = new Test('str2', 'str3');
no parameter
one parameter: str2
two parameters: str2 ; str3

  

六、扩展静态类方法
扩展方法的核心三要素是静态类,静态方法,和this参数。

既在静态类中定义的静态方法,该方法的第一个参数带this

namespace 计算3
{
    public class Program
    {
        static void Main(string[] args)
        {
            string name = "233";
            name.TestString();
            int age = 3;
            age.TestInt();
           
            Console.ReadKey();
        }
    }
 
    public static class Espandi
    {
        public static void TestString(this string s)
        {
            Console.WriteLine("这是 string 的扩展方法:" + s);
        }
 
        public static void TestInt(this int t)
        {
            Console.WriteLine("这是 int 的扩展方法:" + t);
        }
    }
}

  

在上面的 TestString 方法中,参数前面加 this ,可以理解为 给 string 类 添加了一个 静态方法 TestString,那么我们可以在其他的类中使用 string 类型变量直接调用这个方法了,而不需要使用 Espandi.TestString() 这种方式调用。

输出

 上面的效果并不是那么明显,这个案例应该清晰很多

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Test4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string name = "老王";
            name.Test(5);
 
            Console.ReadKey();
        }
    }
 
    public static class lib
    {
        public static void Test(this string name, int age)
        {
            Console.WriteLine("name:{0}, age:{1}",name,age);
        }
    }
}

  运行:

 这个扩展方法,最大的好处就是调用的时候少写一个参数吧,想不出其他的好处了

 

posted @ 2024-02-23 15:36  yinghualeihenmei  阅读(99)  评论(0编辑  收藏  举报