C#:this的指向问题

问题描述:this的指向问题

在c#中this适用多个场合,针对每一个场合所代表的含义又有所不同,根据样例进行分析和介绍:
首先this的总体作用是:this关键字指代类的当前实例,还可用作扩展方法的第一个参数的修饰符。
(1)this代表当前类的实例对象
(2)结构的实例构造函数中出现的this作为一个变量类型,它表示对正在构造的方法的结构的引用
(3)this为原始类型扩展参数,可以将现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型
(4)this可以声明索引器

具体分析:

(1)this指代当前类的实例对象

   public double x, y;
        public Point(double x, double y)
        {
            this.x = x;	//this在实例方法体Point内de1引用当前对象
            this.y = y;
        }

(2)this在构造函数的使用

 public   class 	Test
{
    public  test(Employee E)
    {
        return 0.08m * E.Salary;
    }
}
test(this);

(3)为原始类型扩展参数
例如:public static List ToList(this string Json),就是为this对应的string类型扩展类ToList()方法,调用方式 strJson.ToList();

public static class StringExtension
{
   public static int WordCount(this String str)
   {
    return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
   }
}
}


namespace Extension_Methods_Simple
{

using CustomExtensions;
class Program
{
   static void Main(string[] args)
   {
    string s = "The quick brown fox jumped over the lazy dog.";
    int i = s.WordCount();
    System.Console.WriteLine("Word count of s is {0}", i);
   }
}
}

上述的代码中是在MyExtensions.StringExtension 类中实现了一个名为 WordCount 的扩展方法。该方法对 String 类进行操作,而该类被指定为第一个方法参数。MyExtensions 命名空间被导入到应用程序命名空间中,并且该方法是在 Main 方法内调用的。
(4)索引器的使用
例子://定义一个 Name 属性来操作 name 字段

    public string **Name**
    {
        set { name = value; }
        get { return name; }
    }
    //定义一个 Password 属性来操作 password 字段
    public string **Password**
    {
        set { password = value; }
        get { return password; }
    }
    //定义索引器,name 字段的索引值为 0 ,password 字段的索引值为 1
    public string this[int index]
    {
        get
        {
            if (index == 0) return name;
            else if (index == 1) return password;
            else return null;
        }
        set
        {
            if (index == 0) name = value;
            else if (index == 1) password = value;
        }
    }
}

💪(ง •_•)ง✔

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值