“this”关键字在c#中有多少上下文?
本文关键字:多少 上下文 this 关键字 | 更新日期: 2023-09-27 18:18:38
c#中的关键字this
与其他语言略有不同。我在谷歌上搜索了一段时间,但我找不到一篇能概括这一切的文章。
如何在c#中使用this
?
什么是" this " ?它是许多面向对象编程语言中用于引用当前对象的关键字。它可以被实现为指针(如c++)或引用(如Java),但在c#中它有一些不同的含义。
我们可以在三种不同的上下文中使用" this "
- 调用其他施工
- 引用实例字段或方法
- 传递当前对象
的例子:
public class Person
{
private string name;
public Person()
{
name = "John";
}
public Person(string name)
: this() // call other constructor
{
// this is used to qualify the field
// “name” is hidden by parameter
this.name = name;
}
public string Name
{
get { return name; }
}
private void sayHi()
{
Console.WriteLine("Hi");
Foo.SayName(this); //use this to pass current object
}
public void Speak()
{
this.sayHi(); // use this to refer to an instance method
Console.WriteLine("Want to come up and see my etchings? ");
}
}
class Foo
{
public static void SayName(Person person)
{
Console.WriteLine("My name is {0}", person.Name);
}
}
索引器
为该类型定义一个索引器,使其具有类似数组的语义。
public int this[int index]
{
get { return array[index]; }
set { array[index] = value; }
}
扩展方法
class Foo
{
// with “this” modifiler we can use it like instance method of Person
public static void SayName(this Person person)
{
Console.WriteLine(“My name is {0}”, person.Name);
}
}
struct MyVeryOwnInteger
{
private int x;
public int Gimme()
{
// inside struct this is treated as a variable
// not reference to current structure
return this.x;
}
"this"有两种含义。您(我假设)熟悉的"this",这是指您所在类的当前实例的关键字,然后作为扩展方法中的关键字:
。
public static void SomeExtensionMethod(this string foo)
{
///stuff
}
在后一种情况下,"this"关键字用于表示您正在向强类添加扩展方法。
您可以这样使用它:
假设你有一个类,其中你有一个变量与你给方法的参数同名,当你想在方法外部引用变量时,在这个类中你使用this.variable
。
的例子:
class C:
private str var;
public C(string var)
{
this.var = var;
}
正如我所说的,this.var
指的是"外部"字符串,var
指的是方法的文本中的字符串,在本例中是构造函数。
文档非常清晰,有一些很好的例子。