【问题标题】:Why and when should I use "this" to access methods from base class during inheritance in c#? [duplicate]为什么以及何时应该在 C# 继承期间使用“this”来访问基类中的方法? [复制]
【发布时间】: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


【解决方案1】:

最常见的用途是方法/函数中的变量与另一个类级变量同名。

在这种情况下,使用 this 关键字将告诉编译器您指的是类的变量。

例如:

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”等。

【讨论】:

  • 从未想过 ID 会被这样对待,从现在开始会牢记这一点!
猜你喜欢
  • 1970-01-01
  • 2013-01-29
  • 2016-12-12
  • 1970-01-01
  • 2012-11-15
  • 2020-02-12
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
相关资源
最近更新 更多