为什么以及何时应该使用 "this" 在 c# 继承期间从基 class 访问方法?
Why and when should I use "this" to access methods from base class during inheritance in c#?
Noobie 在这里,但我想知道为什么以及什么时候我需要使用 "this" 关键字来访问 GoldenCustomer 中的 Promote 方法,因为 GoldenCustomer 是从基础 class 哪个客户已经有这个方法了?看到在线课程中使用了 "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;
}
}
最常见的用法是 method/function 中的变量与另一个 class 级变量同名。
在这种情况下,使用 this
关键字将告诉编译器您指的是 class 的变量。
例如:
public class Customer
{
public string Name { get; set; }
Public Customer (string Name, string Id)
{
this.Name = Name; // "this.Name" is class's Name while "Name" is the function's parameter.
}
}
MSDN Doc for other uses and further reading
此外,一个小的旁注:ID 应始终存储为 string
,因为 int
的最大值为 2147483648
,并且 ID 无论如何都被视为字符串(你永远不会在上面使用与数学相关的函数,例如 Id++
或 Id = Id * 2
)。
我指的显然是国家颁发的 ID,例如“6480255197”,而不是“1”、“2”等。
Noobie 在这里,但我想知道为什么以及什么时候我需要使用 "this" 关键字来访问 GoldenCustomer 中的 Promote 方法,因为 GoldenCustomer 是从基础 class 哪个客户已经有这个方法了?看到在线课程中使用了 "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;
}
}
最常见的用法是 method/function 中的变量与另一个 class 级变量同名。
在这种情况下,使用 this
关键字将告诉编译器您指的是 class 的变量。
例如:
public class Customer
{
public string Name { get; set; }
Public Customer (string Name, string Id)
{
this.Name = Name; // "this.Name" is class's Name while "Name" is the function's parameter.
}
}
MSDN Doc for other uses and further reading
此外,一个小的旁注:ID 应始终存储为 string
,因为 int
的最大值为 2147483648
,并且 ID 无论如何都被视为字符串(你永远不会在上面使用与数学相关的函数,例如 Id++
或 Id = Id * 2
)。
我指的显然是国家颁发的 ID,例如“6480255197”,而不是“1”、“2”等。