谁能解释一下“this”在 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
关键字是对类当前实例的引用。
在您的示例中,this
用于引用类 Complex
的当前实例,它消除了 int real
中的歧义构造函数的签名与类定义中的 public int real;
。
MSDN has some documentation这一点也值得一试。
虽然与您的问题没有直接关系,但在 extension methods 中还有另一种使用 this
作为第一个参数的方法。 .它用作第一个参数,表示要使用的实例。如果想向 String 类
添加一个方法,您可以简单地在任何静态类中编写
public static string Left(this string input, int length)
{
// maybe do some error checking if you actually use this
return input.Substring(0, length);
}
关于c# - C#中 "this"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270774/