您的位置:首页 > 其它

this关键字的作用

2012-04-29 18:09 120 查看
1)限定被相似名称隐藏的成员:例如

public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}

2)将对象作为参数传递给其他方法

class Employee
{
private string strName;
private string strAlias;
public static int n = 3;

public Employee(string strName)
{
this.strName = strName;
}

public Employee(string strName,string strAlias)
:this(strName)
{
this.strAlias = strAlias;
}

public void PrintEployee()
{
Console.WriteLine("首先是:被相似名称隐藏的成员:");
Console.WriteLine("Name:{0}\nAlias:{1}", strName, strAlias);
Console.ReadLine();

Console.WriteLine("下面是传递this实例:");
Console.WriteLine("Tax:{0}", Tax.CallTax(this));
Console.ReadLine();
}

public int TestN
{
get { return n; }
set { n = value; }
}
}

class Tax
{
public static int CallTax(Employee e)
{
return 1000*e.TestN;
}
}
class Program
{
static void Main(string[] args)
{
Employee employee = new Employee("张三", "王二");
employee.PrintEployee();
}
}

3)声明索引器(待续)

注:this是针对于对象而言的,所以静态成员不能应用this
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  this