C#this的五种用法

this的五种用法:

1.使用被掩盖的成员变量:

class AA

{

        int a;

        public void set1(int a)

        {

            this.a = a;//right

        }

        public void set2(int a)

        {

            a = a;//会有警告:“对同一变量进行赋值;是否希望对其他变量赋值?”;

        }

}

2.把这个对象传给其他函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class BB
    {
        static public void set(AA t,int a)
        {
            t.set1(a);
        }
    }
    class AA
    {
        int a;
        public void set1(int a)
        {
            this.a = a;
        }
        public void set2(int a)
        {
            BB.set(this, a);
        }
        public int get()
        {
            return a;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            AA t = new AA();
            t.set2(123);
            Console.WriteLine(t.get());
        }
    }
}

 

3.With Indexers(索引器)//这个暂时不懂

4.调用其他构造函数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class AA
    {
        int a, b;
        public AA(int a)
        {
            this.a = a;
            b = -1;
            print();
        }
        public AA(int a,int b):this(a)
        {
            this.b = b;
            print();
        }
        void print()
        {
            Console.WriteLine("{0} {1}", a, b);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            AA t = new AA(1);
            t = new AA(1, 1);
        }
    }
}

输出:

1 -1

1 -1

1 1

5.是代码更明确

如把

        public AA(int a)
        {
            this.a = a;
            b = -1;
            print();
        }    

改为

        public AA(int a)
        {
            this.a = a;
            this.b = -1;
            print();
        }

 

posted on 2015-03-31 21:17  wos1239  阅读(197)  评论(0编辑  收藏  举报

导航