码迷,mamicode.com
首页 > Windows程序 > 详细

C#this的五种用法

时间:2015-03-31 21:53:35      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

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();
        }

 

C#this的五种用法

标签:

原文地址:http://www.cnblogs.com/wos1239/p/4382045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!