C#中this的用法

本文详细介绍了C#中`this`关键字的五个主要用途:1) 限定隐藏成员;2) 作为方法参数传递对象;3) 声明和使用索引器;4) 连接构造函数;5) 扩展原始类型的方法。通过实例展示了`this`在实际编程中的应用,帮助理解其在类和对象交互中的角色。
摘要由CSDN通过智能技术生成

一、限定类似名称隐藏的成员

public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        this.name = name;
        this.alias = alias;
    }
}

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

class Employee
{
    private decimal salary = 3000.00m;
    public void printEmployee()
    {
        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()
    {
        Employee E1 = new Employee();
        E1.printEmployee();
    }
}

在这里插入图片描述

三、声明索引器

1.索引器

静态成员函数,因为它们存在于类级别且不属于对象,不具有 this 指针。 在静态方法中引用 this 会生成错误。

索引器允许类或者结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于他们的访问采用参数。

2.索引器与数组的区别

(1)索引器的索引值(Index)类型不限定为整数

用来访问数组的索引值(Index)一定为整数,而索引器的索引值类型可以定义为其他类型。

(2)索引器允许重载

一个类不限定为只能定义一个索引器,只要索引器的函数签名不同,就可以定义多个索引器,可以重载它的功能。

(3)索引器不是一个变量

索引器没有直接定义数据存储的地方,而数组有。索引器具有Get和Set访问器。

3、索引器与属性的区别

(1)索引器以函数签名方式 this 来标识,而属性采用名称来标识,名称可以任意
(2)索引器可以重载,而属性不能重载。
(3)索引器不能用static 来进行声明,而属性可以。索引器永远属于实例成员,因此不能声明为static。

1.以字符串作为下标,对索引器进行存取
2. 多参数索引器及索引器的重载

两个案例点击查看

public class IDXer
{
    private string[] name = new string[10];

    //索引器必须以this关键字定义,其实这个this就是类实例化之后的对象
    public string this[int index]
    {
        get
        {
            return name[index];
        }
        set
        {
            name[index] = value;
        }
    }
}

public class Program
{
    static void Main(string[] args)
    {
        //最简单索引器的使用           
        IDXer indexer = new IDXer();
        //“=”号右边对索引器赋值,其实就是调用其set方法
        indexer[0] = "张三";
        indexer[1] = "李四";
        //输出索引器的值,其实就是调用其get方法
        Console.WriteLine(indexer[0]);
        Console.WriteLine(indexer[1]);
        Console.ReadKey();
    }
}

四、用this串联构造函数

使用this会调用无参构造函数

// See https://aka.ms/new-console-template for more information
public class Test
{
    public Test()
    {
        Console.WriteLine("无参构造函数");
    }
    // this()对应无参构造方法Test()
    // 先执行Test(),后执行Test(string text)
    public Test(string text) : this()
    {
        Console.WriteLine(text);
        Console.WriteLine("有参构造函数");
    }
    public Test(string text,string name) : this()
    {
        Console.WriteLine(text);
        Console.WriteLine(name);
        Console.WriteLine("有两个参构造函数");
    }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            Test test = new Test("张三","lisi");
            Test test1 = new Test("李四");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        finally
        {
            Console.ReadLine();
        }
    }
}

在这里插入图片描述

五、为原始类型扩展方法

当我们需要给一个类增加方法,但又不希望修改这些类,也不希望创建这些类的子类,可以采用扩展方法。扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用

MyClass 是需要扩展的类

using System;

// 自定义类
public class MyClass
{
    public int Value { get; set; }

    public MyClass(int value)
    {
        Value = value;
    }
}

// 静态扩展方法类,给MyClass扩展了DoubleValue函数
public static class MyClassExtensions
{
    // 扩展方法示例:将 MyClass 对象的值翻倍
    public static int DoubleValue(this MyClass obj)
    {
        return obj.Value * 2;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass myObject = new MyClass(5);

        // 使用扩展方法
        int doubledValue = myObject.DoubleValue();

        Console.WriteLine($"Original Value: {myObject.Value}");
        Console.WriteLine($"Doubled Value: {doubledValue}");
    }
}

扩展string

using System;

public static class StringExtensions
{
    // 扩展方法示例:反转字符串
    public static string Reverse(this string str)
    {
        char[] charArray = str.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string original = "Hello, World!";
        string reversed = original.Reverse();

        Console.WriteLine("Original: " + original);
        Console.WriteLine("Reversed: " + reversed);
    }
}

  • 15
    点赞
  • 110
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有诗亦有远方

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值