gpt4 book ai didi

c# - 在 Getter 方法中使用 'this' 关键字?

转载 作者:太空宇宙 更新时间:2023-11-03 18:59:11 24 4
gpt4 key购买 nike

public string GetTitle()
{
return title;
}

正如您在上面的代码中看到的,在 GetTitle() 方法中,它被用来返回标题实例变量。我的问题是,如果我添加“this”关键字使得 GetTitle() 方法变为如下所示,会有什么不同:

public string GetTitle()
{
return this.title;
}

我还没有在书中或任何地方看到过后者的例子。但我在 Visual Studio 中尝试过,它仍然做同样的事情。

请有人解释一下有什么区别吗?

谢谢! :)

最佳答案

Please can someone explain what the difference is, if any?

两者之间没有任何区别:

public string GetTitle()
{
return title;
}

还有这个:

public string GetTitle()
{
return this.title;
}

this 指的是类的实例。因此,您可以作为 titlethis.title 访问该字段。

但是,我没有看到任何遵循上述定义 getter 和 setter 的方法。除了遵循上述方法,您还可以使用以下语法来实现相同的目的:

public string Title { get; set; }

每当你想阅读Title时,你只需使用以下内容

classInstance.Title

无论什么时候你想设置它的值,你只需使用下面的:

classInstance.Title = "your title";

在这两种情况下,classInstance 顾名思义是您的类的一个实例。

值得注意的是,上面的内容称为自动实现的属性。在此之前,您唯一可以执行相同操作的方法如下:

private string title;
public string Title
{
get { return title; }
set { title = value; }
}

现在,只要您想在 getset 中应用任何逻辑,就会使用以下语法。如果不是这种情况,则通常会遵循自动实现的属性方法,因为它更紧凑。

关于c# - 在 Getter 方法中使用 'this' 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38815259/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com