c#中的this关键字示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace this_example { public class Demo { string firstname; string secondname; public Demo(string firstname, string secondname) { firstname = firstname; secondname = secondname; } public void Show() { Console.WriteLine("Your firstname is :" + firstname); Console.WriteLine("Your secondname is : " + secondname); } } class abc { static void Main(string[] args) { string _firstname; string _secondname; Console.WriteLine("Enter your firstname : "); _firstname = Console.ReadLine(); Console.WriteLine("Enter your secondname : "); _secondname = Console.ReadLine(); Demo obj = new Demo(_firstname, _secondname); obj.Show(); Console.Read(); } } }
上面的程序,将不会输出结果。因为本地的变量优先于对象的成员变量。
使用this 关键字
通过this,我们指定访问的是对象的成员变量。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace this_example { public class Demo { string firstname; string secondname; public Demo(string firstname, string secondname) { this.firstname = firstname; this.secondname = secondname; } public void Show() { Console.WriteLine("Your firstname is :" + firstname); Console.WriteLine("Your secondname is : " + secondname); } } class abc { static void Main(string[] args) { string _firstname; string _secondname; Console.WriteLine("Enter your firstname : "); _firstname = Console.ReadLine(); Console.WriteLine("Enter your secondname : "); _secondname = Console.ReadLine(); Demo obj = new Demo(_firstname, _secondname); obj.Show(); Console.Read(); } } }
在c#中的this关键字是指类的当前实例。
它可用于从构造函数,实例方法和实例访问器中访问成员。
静态构造函数和成员方法没有this指针,因为它们不是实例化的。
日期:2020-04-11 23:03:53 来源:oir作者:oir