c# - C#中 "this"是什么意思

标签 c#

谁能解释一下“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); 
}

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

关于c# - C#中 "this"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6270774/

相关文章:

c# - 如何解决 Xamarin 中的错误 'Property is null or is not IEnumerable'

c# - 对象引用未设置到对象模型 fk 和虚拟字段的实例

C# 算法 - 找到最少数量的必要对象

c# - 恢复下载

c# - 异步套接字服务器和AS3 Flash应用程序-未处理用户断开连接

c# - 保存 RichTextBox 的文本

c# - ASP.NET 从 Session 中删除一个项目?

c# - 绑定(bind)到列表的模型抛出 "Collection is read-only"异常

c# - 创建缩略图会产生质量很差的图像

c# - MEF 导出中的 ExpandoObject