C#中"this"的含义是什么

use*_*784 6 c#

有人可以在C#中解释"this"的含义吗?

如:

// 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;
   }
Run Code Online (Sandbox Code Playgroud)

Nat*_*ate 15

this关键字是将类的当前实例的引用.

在您的示例中,this用于引用类的当前实例,Complex它消除int real了构造函数的签名与public int real;类定义之间的歧义.

MSDN也有一些相关的文档,值得一试.

虽然与您的问题没有直接关系,但this在扩展方法中还有另一种用作第一个参数.它用作表示要使用的实例的第一个参数.如果想要添加一个方法,String 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); 
}
Run Code Online (Sandbox Code Playgroud)

另请参阅:http://msdn.microsoft.com/en-us/library/bb383977.aspx