c#中this的用法及含义

xue_er111 2010-12-06 06:28:51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 派生类构造函数及其调用
{
class Program
{
static void Main(string[] args)
{
Point a=new Point ();
Circle b=new Circle (3.5);
Circle c=new Circle (1,1,4.8);
Console.Read();
}
}
class Point
{
private int x, y;
public Point()
{
x = 0; y = 0;
Console.WriteLine("Point()constructor:{0}", this);
}
public Point(int x, int y)
{
this.x = x;
this.y = y;
Console.WriteLine("Point(x,y)constructor:{0}", this);
}
}
class Circle : Point
{
private double radius;
public Circle()//默认约定调用基类的无参构造函数Point()
{
Console.WriteLine("Circle()constructor:{0}", this);//this代表什么意思
}
public Circle(double radius)
: base()
{
this.radius = radius;
Console.WriteLine("Circle(radius)constructor:{0}", this);
}
public Circle(int x, int y, double radius)
: base(x, y)
{
this.radius = radius;
Console.WriteLine("Circle(x,y,radius)constructor:{0}", this);
}
}
}请问以下this在这里是什么意思,应该输出什么
...全文
814 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
grasshopperwarbler 2010-12-06
  • 打赏
  • 举报
回复
this 就是"这个"的意思.

用你这个例子来说,假如你新建了几个Point类,它们叫做a,b或其他什么的。
你只想给a赋值,那么在新建a的时候就要调用它的构造函数Point。
就是这句
public Point(int x, int y)
{
this.x = x;
this.y = y;
Console.WriteLine("Point(x,y)constructor:{0}", this);
}

意思就是,a的x值等于传过来的int x, a的y值等于传来的y。试想想,如果没有这个this,是不是变成x=x了?

刚学面向对象的语言的时候this是很重要的概念,希望我的解释能帮楼主更好地理解。
xpcxpy 2010-12-06
  • 打赏
  • 举报
回复
构造函数中 this就代表的是当前类
xpcxpy 2010-12-06
  • 打赏
  • 举报
回复
2楼正确
qyshice 2010-12-06
  • 打赏
  • 举报
回复
this 引用现在所用类的实例对象
灬嘻嘻哈哈灬 2010-12-06
  • 打赏
  • 举报
回复
this 就是该类的当前实例。。
输出的话等同于 this.ToString() 。。
在这里输出类名。。
wuyq11 2010-12-06
  • 打赏
  • 举报
回复
引用类的当前实例
base关键字其用于在派生类中实现对基类公有或者受保护成员的访问
this用于引用类的当前实例,也包括继承而来的方法,通常可以隐藏this
限定被相似的名称隐藏的成员
将对象作为参数传递到其他方法
声明索引器

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧