c#中this

本文详细介绍了C#中this关键字的多种用途,包括表示当前对象、在构造函数中传递自身实例、实现索引器功能及为基本类型扩展方法等。通过具体示例展示了this关键字如何提高代码的清晰度和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.和c++中一样,指当前的对象。

2.用于传递构造函数。eg

class TestA
{
    public TestA()
    {
        Console.WriteLine("Default Constructor");
    }
    public TestA(int a)
        : this()
    {
        Console.WriteLine("One parameter Constructor {0}",a);
    }
    public TestA(int a, int b)
        : this(a)
    {
        Console.WriteLine("2 parameter constructor");
    }
}

3.用于实现索引:

  public class IndexTest
    {
        int[] a = new int[10];

        public int this[int index]
        {
            get
            {
                return a[index];
            }
            set
            {
                a[index] = value;
            }
        }
    }

 这样就可以直接使用IndexTest对象的[]操作。

4.为原始类型扩展方法 

扩张方法三要素:

  • 静态类。
  • 静态函数
  • this关键字

比如扩展string


    //1.静态类
    public static class ExtentString
    {
        //静态函数+this.length是Fun函数的第一个参数。
        public static int Fun(this string s, int length)
        {
            return s.Length + length;
        }
    }

 


使用的时候:

        string _tempstring  = "sfsfa";
        _tempstring.Fun(10);

 

 

 

  

转载于:https://www.cnblogs.com/bingbingzhe/p/7132237.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值