问题描述: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;
}
}
}
💪(ง •_•)ง✔