“this”是什么意思? c#中的关键字 [英] What is the meaning of the "this" keyword in c#

查看:94
本文介绍了“this”是什么意思? c#中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好b $ b

   编程中的关键字?

解决方案

它是对当前对象的引用,如果你来自那个背景,则与我在VB中相同。

this关键字指的是您当前正在其中编写代码的类。我主要使用它来区分方法参数和类字段。



例如,我们假设您有以下类:



  public   class  Person 
{
string name = ; // 类Person中的字段name

// Person类的构造函数,取名人的名字
// 作为参数
public Person( string name)
{
// 赋值字段name的构造函数参数name
this .name = name;
// 如果你在这里错过了this(name = name;)你就会将
// 构造函数参数分配给自身和字段name span>
// 人员类将保持其值。
}
}





希望我能说清楚。

您可以找到更多参考根据 MSDN页面 [ ^ ]。



欢呼,

Marco Bertschi


根据您使用它的位置,它有不同的含义: -

1.参考当前类的实例

2.从同一类的构造函数中调用另一个构造函数。

3.Declare indexer

以下示例涵盖3以上

< pre lang =c#> class abc
{
string x; // 班级成员
public abc( string x)
{
// 引用当前实例
.x = x; // (this.x指类成员)
}
// 调用另一个构造函数
public abc(): this xyz // 在abc()之前调用abc(字符串x)
{
}
// 声明索引器
public int [ int index]
{
get { return x [index];}
set {x [index] = value ;}
}



4.还使用过在扩展方法



这些我知道this关键字的一些含义。


Hi
What is the meaning of the

this

keyword in c# programming?

解决方案

It is a reference to the current object, the same as My in VB if you are coming from that background.


The "this" keyword refers to the class which you are currently writing code in it. I mainly use it to distinct between method parameters and class fields.

For example, let's assume you have the following class:

public class Person
{
   string name = ""; //Field "name" in class Person
   
   //Constructor of the Person class, takes the name of the Person
   //as argument
   public Person (string name)
   {
       //Assign the value of the constructor argument "name" to the field "name"
       this.name = name; 
       //If you'd miss out the "this" here (name = name;) you would just assign the
       //constructor argument to itself and the field "name" of the
       //Person class would keep its value "".
   }
}



Hope I could make it clear to you.
You can find additional reference information at the according MSDN page[^].

cheers,
Marco Bertschi


Depending on where you r using it ,it has different meanings:-
1.Reference to current instance of class
2.Call another constructor from a constructor in same class.
3.Declare indexer
Below example covers above 3

class abc
{
string x; //class member
public abc(string x)
{
//referring to current instance
this.x=x;//("this.x" refers to class member)
}
//calling another constructor
public abc():this("xyz")//calls abc(string x) before abc()
{
}
//declaring an indexer
public int this[int index]
{
get{return x[index];}
set{x[index]=value;}
}


4.also used in Extension methods

These are some meanings I know about "this" keyword.


这篇关于“this”是什么意思? c#中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆