C#中this的用法

 

代码
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
// Create objects:
Employee E1 = new Employee("XiaoLong", "Brown"); //创建了一个E1对象
// Display results:
E1.Salary = 30.00m; //虽然已经存在了Salary,在此将E1对象的Salary属性重新赋一次值
E1.printEmployee();
}
}
class Employee
{
private string name;
private string alias;
private decimal salary;
// Constructor:
public Employee(string name, string alias)
{
this.name = name;
this.alias = alias;
}
// Printing method:
public void printEmployee()
{
MessageBox.Show(
"Name:" + name + "\r\n" + "Alias : " + alias + "\r\n" + "Taxes:" + Employee.CalcTax(this));
// Passing the object to the CalcTax method by using this:
}
public decimal Salary
{
get
{
return salary ;
}
set
{
salary
= value;
}
}
public static decimal CalcTax(Employee E)
{
return 0.08m * E.Salary;
}
}

}

可以更好的理解,printEmployee中的this表示为类的当前对象,也就是E1对象。

运行结果为:

 

posted @ 2010-03-14 22:10  平凡人生  阅读(335)  评论(0编辑  收藏  举报