C#this关键字的四种⽤法本⽂实例为⼤家分享了C# this关键字的四种⽤法,供⼤家参考,具体内容如下
⽤法⼀  this代表当前实例,⽤this.显式调⽤⼀个类的⽅法和成员
namespace Demo
{
public class Test
{
private string scope = "全局变量";
public string getResult()
{
string scope = "局部变量";
       // 在这⾥,this代表Test的实例,所以this.scope指向的是全局变量,scope所访问的是局部变量      return this.scope + "-" + scope;
}
}
class Program
{
static void Main(string[] args)
{
try
{
Test test = new Test();
Console.Result());
}
writeline函数
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}
}
}
⽤法⼆通过this实现原始类型的扩展(下⼀篇详解)
⽤法三通过this实现索引器,可⽤于优化程序性能(下⼀篇详解)
⽤法四⽤this串联构造函数
namespace Demo
{
public class Test
{
public Test()
{
Console.WriteLine("⽆参构造函数");
}
// 这⾥的this()指向的是Test()⽆参构造函数
/
/ 相当于继承了⽆参构造函数
public Test(string text) : this()
{
// 程序进来后会先执⾏Test()⽆参函数,然后继续往下边执⾏
Console.WriteLine(text);
Console.WriteLine("有参构造函数");
}
}
class Program
{
static void Main(string[] args)
{
try
{
Test test = new Test("张三");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}
}
}
}
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。