【发布时间】:2019-09-15 19:49:59
【问题描述】:
Noobie 在这里,但我想知道为什么以及何时需要使用“this”关键字来访问 GoldenCustomer 中的提升方法,因为 GoldenCustomer 是从已经具有此方法的基类 Customer 派生的?看到在线课程中使用了“this”,但不禁想知道。
编辑: 不,我的问题不是重复的,因为另一个问题没有回答何时以及是否有必要在继承期间使用“this”。
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Promote();
GoldCustomer goldCustomer = new GoldCustomer();
goldCustomer.OfferVoucher();
}
}
public class GoldCustomer : Customer{
public void OfferVoucher(){
this.Promote(); //why is this used here?
}
}
public class Customer{
public int Id { get; set; }
public string Name { get; set; }
public void Promote(){
int rating = CalculateRating(excludeOrders: true);
if (rating == 0)
System.Console.WriteLine("Promoted to level 1");
else
System.Console.WriteLine("Promoted to level 2");
}
private int CalculateRating(bool excludeOrders){
return 0;
}
}
【问题讨论】:
-
除非您的类成员和方法参数具有相同的名称,否则您实际上不必使用
this。比你必须明确地说this.name代表成员或name代表论点。我不知道需要时有任何其他情况。 -
在您的示例中,它什么也不做,与没有它的代码完全相同。
-
@iakobski 你的意思是在我的例子中具体还是在所有类似的情况下?
-
阅读上面的链接,但我可以说,在整个代码库中,我们唯一的用途是在扩展方法或构造函数中。最常见的情况是参数和类变量之间存在名称冲突。这是因为遵守命名标准,可以通过使用私有属性来避免。
-
“另一个问题没有回答何时以及是否有必要在继承期间使用“this”” - 它没有具体解决这个问题,因为使用 @ 987654325@ 与继承无关。将“继承”一词或任何其他类似地添加零新上下文的词添加到问题中不会改变问题作为另一个重复的固有性质。
标签: c# oop inheritance this