C中的this

作者:郑凯丰
开发工具:VS、C#
编写日期:2019年7月26日

第一种、
namespace Demo
{
public class Test //this代表的是他的
{
private string scope = “全局变量”;//然后对应这个全局变量
public string getResult()
{
string scope = “局部变量”; //再对应这个局部变量
return this.scope + “-” + scope;
}
}
class Program
{
static void Main(string[] args)
{
try
{
Test test = new Test();
Console.WriteLine(test.getResult());
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}

    }
}

}

第二种、
namespace Demo
{
public class Test
{
public Test()
{
Console.WriteLine(“无参构造函数”);
}
// this()对应无参构造方法Test()
// 先执行Test(),后执行Test(string text)
public Test(string text) : this()
{
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();
}
}
}
}


版权声明:本文为weixin_44540479原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。