C# this关键字详解

this关键字主要有一下几个用途:
1,this 用来引用当前类的实例,和扩展方法的第一个参数的修饰符
}
2,
限定被相似的名称隐藏的成员,例如:
public Employee(string name, string alias)
{
    // Use this to qualify the fields, name and alias:
    this.name = name;
    this.alias = alias;
}

 3.将对象作为参数传递到其他方法,例如:

CalcTax(this);
3.声明索引器
public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

在本例中,this 用于限定 Employee 类成员 name 和 alias,它们都被相似的名称隐藏。 该关键字还用于将对象传递到属于其他类的方法 CalcTax。

  static void Main(string[] args)
        {
            Employee e = new Employee("james");
            e.printEmployee();
        }
        public class Employee
        {
            private string name;
            private decimal salary = 3000.00m;
            public Employee(string name)
            {
                this.name = name;
            }
            public void printEmployee()
            {
                Console.WriteLine("Name: {0}", name);

                Console.WriteLine("Taxes: {0:C}", Tax.CalcTax(this));
                Console.Read();
            }
            public decimal Salary
            {
                get { return salary; }
            }
        }
        class Tax
        {
            public static decimal CalcTax(Employee E)
            {
                return 0.08m * E.Salary;
            }
        }
    }
View Code

 

posted @ 2015-03-15 22:19  jingfeng.Kang  阅读(208)  评论(0编辑  收藏  举报