• C# - this 的用法


    引言

    最近有接触到 C# 静态方法中 this 做为参数紧跟类名,实现对类的扩展。觉得很好奇,便想了解一下 C# 中 this 关键字的用法,主要有 5 类用法。

    内容提要:

    1. 限定类似名称隐藏的成员
    2. 将对象作为参数传递给方法
    3. 声明索引器
    4. 串联构造函数
    5. 扩展方法

    限定类似名称隐藏的成员

    this 区别类成员和参数

    public class Employee
    {
        private string alias;
        private string name;
    
        public Employee(string name, string alias)
        {
            // Use this to qualify the members of the class
            // instead of the constructor parameters.
            this.name = name;
            this.alias = alias;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    将对象作为参数传递给方法

    Tax.CalcTax(this)

    class Employee
    {
        private string name;
        private string alias;
        private decimal salary = 3000.00m;
    
        // Constructor:
        public Employee(string name, string alias)
        {
            // Use this to qualify the fields, name and alias:
            this.name = name;
            this.alias = alias;
        }
    
        // Printing method:
        public void printEmployee()
        {
            Console.WriteLine("Name: {0}\nAlias: {1}", name, alias);
            // Passing the object to the CalcTax method by using this:
            Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
        }
    
        public decimal Salary
        {
            get { return salary; }
        }
    }
    
    class Tax
    {
        public static decimal CalcTax(Employee E)
        {
            return 0.08m * E.Salary;
        }
    }
    
    class MainClass
    {
        static void Main()
        {
            // Create objects:
            Employee E1 = new Employee("Mingda Pan", "mpan");
    
            // Display results:
            E1.printEmployee();
        }
    }
    /*
    Output:
        Name: Mingda Pan
        Alias: mpan
        Taxes: $240.00
     */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    声明索引器

    索引器类似于属性。 很多时候,创建索引器与创建属性所使用的编程语言特性是一样的。 索引器使属性可以被索引:使用一个或多个参数引用的属性。 这些参数为某些值集合提供索引。

    使用 this 关键字作为属性名声明索引器,并在方括号内声明参数。

    namespace ConsoleApp1
    {
        public class IndexExample
        {
            private string[] nameList = new string[10];
            public string this[int index]
            {
                get { return nameList[index]; }
                set { nameList[index] = value; }
            }
            public int this[string name]
            {
                get
                {
                    for(int i = 0; i < nameList.Length; i++)
                    {
                        if(nameList[i] == name) return i;
                    }
                    return -1;
                }
            }
        }
    
        public class Program
        {
            public static void Main(string[] args)
            {
                IndexExample indexExample = new IndexExample();
                indexExample[0] = "Tom";
                indexExample[1] = "Lydia";
                Console.WriteLine("indexExample[0]: " + indexExample[0]);
                Console.WriteLine("indexExample['Lydia']: "+ indexExample["Lydia"]);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    输出:

    indexExample[0]: Tom
    indexExample['Lydia']: 1
    
    • 1
    • 2

    串联构造函数

    this 调用构造函数

    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");
            }
            }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    输出:

    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    扩展方法

    1. 定义包含扩展方法的类必须为静态类
    2. 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
    3. 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
    4. 在调用代码中,添加 using 指令,用于指定包含扩展方法类的 using
    5. 和调用类型的实例方法那样调用这些方法。

    以下示例实现 CustomExtensions.StringExtension 类中名为 WordCount 的扩展方法。 此方法对 String 类进行操作,该类指定为第一个方法参数。 将 CustomExtensions 命名空间导入应用程序命名空间,并在 Main 方法内部调用此方法。

    using System.Linq;
    using System.Text;
    using System;
    
    namespace CustomExtensions
    {
        // Extension methods must be defined in a static class.
        public static class StringExtension
        {
            // This is the extension method.
            // The first parameter takes the "this" modifier
            // and specifies the type for which the method is defined.
            public static int WordCount(this string str)
            {
                return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
            }
        }
    }
    namespace Extension_Methods_Simple
    {
        // Import the extension method namespace.
        using CustomExtensions;
        class Program
        {
            static void Main(string[] args)
            {
                string s = "The quick brown fox jumped over the lazy dog.";
                // Call the method as if it were an
                // instance method on the type. Note that the first
                // parameter is not specified by the calling code.
                int i = s.WordCount();
                System.Console.WriteLine("Word count of s is {0}", i);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    同样,我们也可以扩展任意自定义类。
    在这里插入图片描述

    Test 类:

    namespace ConsoleApp1
    {
        public class Test
        {
            public Test()
            {
                Console.WriteLine("constructor method");
            }
            public void myMethod()
            {
                Console.WriteLine("this is MyMethod");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Test 扩展类,定义了一个扩展方法:

    namespace ConsoleApp1.ExtendMethod
    {
        public static class TestExtend
        {
            public  static void ExtendMethod(this Test t)
            {
                Console.WriteLine("this is extention method");
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    测试一下:扩展方法就跟自己的方法一样,可以调用。

    using ConsoleApp1.ExtendMethod;
    
    namespace ConsoleApp1.Execution
    {
        public class ProgramTest
        {
            static void Main(string[] args)
            {
                Test t1 = new Test();
                t1.myMethod();
                t1.ExtendMethod();
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    输出:

    constructor method
    this is MyMethod
    this is extention method
    
    • 1
    • 2
    • 3
  • 相关阅读:
    LabVIEW对EAST长脉冲等离子体运行的陀螺稳态运行控制
    【GNN报告】加拿大蒙特利尔学习算法研究所 (Mila)博后研究员张文涛: 大规模图机器学习
    Python笔记 - generator方法
    欧科云链研究院:如何降低Web3风险,提升虚拟资产创新的安全合规
    矩阵点乘multiply()函数和矩阵乘法dot()函数
    【java苍穹外卖项目实战三】nginx反向代理和负载均衡
    VirtualAllocAPi逆向笔记
    【数据挖掘】生成模型和判别模型的区别及优缺点
    软件工程师必读的13本书
    通过隧道功能在安全标准较高的情况下访问Linux
  • 原文地址:https://blog.csdn.net/wumingxiaoyao/article/details/125818672