zoukankan      html  css  js  c++  java
  • this

    this表示当前的类,所以它只会在本类中使用,到了另一个类,就不是当前的类了。它的基本用法可以用以下代码来表现。
    using System;

    class m
    {
     
    static void Main()
     
    {
      point p
    =new point();
      p.w1(
    15);
     }

    }


    class point
    {
     
    private int x=12;
     
     
    public void w1(int x0)
     
    {
      
    this.x=x0;
      Console.WriteLine(
    this.x);
     }

    }
    但疑问的是,第19行this.x,不必写this也是可以的,得到的结果完全一样,为什么还要多余的this。原来,如果类point中w1的程序写成这样:
     public void w1(int x)
     
    {
      
    this.x=x;
      Console.WriteLine(
    this.x);
     }

    那就非要用this不可了。不过,我实在不敢恭维这种编码习惯。

    刚才说大部分写不写this是没有区别的,但在IDE环境中,如果要在类中调用类中的数据成员或成员函数,写一个this,点一下后,IDE自动感知,把可能的内容列在后面,这样方便我们输入,所以这也是this的一大用途。

    另外,有一些函数,入口参数就是类本身,所以此时则是不得不用this。

    using System;

    static class m
    {
     
    static void Main()
     
    {
      point p
    =new point();
      p.w1();
     }


     
    public static void DrawPoint(point p)
     
    {
      Console.WriteLine(
    "draw point : x=" + p.x.ToString());
     }

    }


    class point
    {
     
    public int x=12;
     
     
    public void w1()
     
    {
       m.DrawPoint(
    this);
     }

    }

    注意:以上代码的类m前面有加一个static,即静态类,DrawPoint这样,point引用时,不必再创建类的实例,直接写m.DrawPoint。后面跟的this就是point类的实例,如果不用this,我就真的不知道应该要用什么了。

    一个类,如果还没设置其它属性,在IDE中,输入this.后,会列出哪些内容?
    我试了一下,有:Equals、GetHashCode、GetType、MemberwiseClone、ToString,与“对象浏览器”的接口中比较,少了ReferenceEquals,多了MemberwiseClone。如果我再加上各种类型的数据成员,则“对象浏览器”中只列出公共变量,而this.下面还会列出私有变量。

  • 相关阅读:
    郭大小
    最近翻译的三篇新闻
    又是一年教师节
    PowerDesigner 12.5 反向工程sql server
    Sql Server使用技巧
    一个纠结的silverlight问题
    PowerDesigner 15 使用技巧
    windows2008 + iis7 下载特殊后缀名文件设置方法
    无法读取配置节system.serviceModel因为它缺少节声明的解决方法
    PowerDesigner 15对ACCESS进行反向工程
  • 原文地址:https://www.cnblogs.com/yzx99/p/1208011.html
Copyright © 2011-2022 走看看