c# - 使用关键字this.实现构造函数有什么区别?

标签 c# constructor reference

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

 public User(string a, string b)

    {

        name = a;

        location = b;

    }

还有这个:

  public User(string a, string b)

    {

        this.name = a;

        this.location = b;

    }

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

最佳答案

没有区别,

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)

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method

关于c# - 使用关键字this.实现构造函数有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53020197/

相关文章:

c# - 我如何在 C# 中解决 Web/Windows 应用程序中的相对路径

c# - 为什么有时 2 个对象引用相同但不总是

c# - 在 C# 中是否应该始终保留对正在运行的 Thread 对象的引用?

c++ - 如何在 C++ 中通过引用分配类实例?

java - 在构造函数中使用 JAXB

c# - Unity C# 中的 2 Int 元组和包含方法

C#构造函数泛型参数推断

c# - 如何在 C# 中使用 NPOI Excel 添加单元格注释?

c++ - C++ 对象成员数组的默认初始化?

java - 使用继承时,静态 block 和初始化 block 按什么顺序执行?