问题描述
有人可以在C#中解释这个的意思吗?
Could anyone please explain the meaning "this" in C#?
例如:
// complex.cs
using System;
public struct Complex
{
public int real;
public int imaginary;
public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}
推荐答案
this
关键字是对该类当前实例的引用。
The this
keyword is a reference to the current instance of the class.
在您的示例中, this
用于引用类 Complex
的当前实例,它消除了 int real
之间的歧义。构造函数的签名与 public int real;
在类定义中。
In your example, this
is used to reference the current instance of the class Complex
and it removes the ambiguity between int real
in the signature of the constructor vs. the public int real;
in the class definition.
,值得一看。
尽管与您的问题没有直接关系,但 this
的另一种用法是扩展方法中的第一个参数。它用作表示要使用的实例的第一个参数。如果要向 String类
添加方法,则可以简单地在任何静态类中编写
Though not directly related to your question, there is another use of this
as the first parameter in extension methods. It is used as the first parameter which signifies the instance to use. If one wanted to add a method to the String class
you could simple write in any static class
public static string Left(this string input, int length)
{
// maybe do some error checking if you actually use this
return input.Substring(0, length);
}
另请参阅:
这篇关于“ this”的含义是什么?在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!