c# this关键字的理解

this关键字引用类的当前实例

1/限定被相似的名称隐藏的成员

2/将对象作为参数传递到其他方法

3/声明索引器

实际案例参考:

//成员类
    public class Employee
    {
        private string _MyName;
        private int _MyAge;
        public string[] _arry = new string[5];

        public string Name { get { return this._MyName; } }

        public int Age { get {return this._MyAge; } }

        public Employee(string name, int age)
        {
            this._MyName = name;
            this._MyAge = age;
        }
        public string this[int param] {
            get { return _arry[param]; }
            set { _arry[param] = value; }
        }

        public void PrintInfo() {
            Print.DoPrint(this);
        }

        //改善C#程序的50种方法
    }
    //打印类
    public class Print {
        public static void DoPrint(Employee e)
        {
            Console.WriteLine("Name:{0}\nAge:{1}",e.Name,e.Age);
        }

    }

执行代码 和结果

 Employee emp = new ConsoleApplication5.Employee("Zmztya",24);
            //打印本人信息
            emp.PrintInfo();
            emp[0] = "Father";
            emp[1] = "Mather";
            emp[2] = "Sister";
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("家庭成员:{0}",emp[i]);
            }
            Console.WriteLine();


结果: Name:Zmztya   Age:24
          家庭成员:father
          ....(省略其他四个,最后两个是空值)
 

this 的关键字并没有发现其他特殊的用法。可以去掉除索引的意外的this,效果是一样的。

posted @ 2016-08-16 14:22  zmztyas  阅读(739)  评论(0编辑  收藏  举报