【问题标题】:What is the difference in implementaton of constructor by using keyword this.?使用关键字 this. 实现构造函数有什么区别?
【发布时间】:2018-10-27 08:47:14
【问题描述】:

请你解释一下这两种构造函数的实现有什么区别:

 public User(string a, string b)

    {

        name = a;

        location = b;

    }

还有这个:

  public User(string a, string b)

    {

        this.name = a;

        this.location = b;

    }

从编译器的角度来看,我没有看到任何区别。请解释一下。

【问题讨论】:

标签: c# constructor reference


【解决方案1】:

没有区别,

this 只是引用类,如果您传入的参数与您的类中的字段名称相同(以区分它们),则它很有用

public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        // Use this to qualify the members of the class 
        // instead of the constructor parameters.
        this.name = name;
        this.alias = alias;
    }
}

其他资源

this (C# Reference)

this 关键字引用类的当前实例并且是 也用作扩展方法的第一个参数的修饰符

【讨论】:

  • 对不同的变量和构造函数参数也使用“this”是一种好习惯,或者它们只是相同的吗?
  • @Heron 在这种情况下我不使用this,有些人喜欢它,因为它很突出,这取决于您喜欢如何编写代码,有些人喜欢私有字段名称以下划线开头。即_field 一些不,如果它对你有帮助,那么就保持一致,就个人而言,我使用下划线作为字段名称,它们会突出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
  • 2014-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多