``this'' in C#

来源:互联网 发布:vb怎么建立数据库 编辑:程序博客网 时间:2024/05/16 11:40

When to use `this' in the code?

  1. To avoid the nameing scopes, e.g.
            public class Rectangle:Shape{        public Rectangle(double Width, double Height):base(){        this.Width = Width;        this.Height = Height;        }        }

    If you have the parameters named as Width and Height, you have to use `this' to avoid ambiguity. Otherwise, you may neglect it as...

            public class Rectangle:Shape{        public Rectangle(double w, double h):base(){        Width = w;        Height = h;        }        }

  2. To refer to the current instance, e.g.

            public interface IIndex<out T>{        T this[int i]{get;}        int Count{get;}        }
    and the implementation of the interface should refer to `this' as well...
            public Rectangle this[int i]{        get{        if(i<0||i>=data.Length){        throw new ArgumentOutOfRangeException("index");                }        return data[i];        }        }



原创粉丝点击