是否需要使用关键字“this”来区分大写和小写?

时间:2021-05-17 12:39:28

标签: c#

  1. 使用大写(姓名)和小写(姓名)时是否需要使用关键字“this”?

  2. 在我的例子中是否有必要使用“:this()”?我什么时候应该使用“:this()”?

我的例子:

namespace SharedCode
{
  public class Friendslist : IState
  {
    public struct MyContainer
    {
      public string Name;
      public string Firstname;
      public int Phonenumber;

      public MyContainer(string name, string firstname, int phonenumber)
           : this()
      {
        this.Name = name;
        this.Firstname = firstname;
        this.Phonenumber = phonenumber;
      }

    }
  }
}

3 个答案:

答案 0 :(得分:4)

不,只有当构造函数中的参数与类中的属性同名时,才应该使用 this

答案 1 :(得分:2)

<块引用>
  1. 使用大写(名称)和小写(名称)时是否需要使用关键字“this”?

没有。 C# 区分大小写。

如果您有与参数同名的字段或属性,那么您需要使用 this. 来消除两者之间的歧义:

struct Foo
{
    private int bar;
    public Foo(int bar)
    {
        this.bar = bar;
    }
}
<块引用>
  1. 在我的例子中是否有必要使用“:this()”?我什么时候应该使用“:this()”?

没有

结构在这里有点奇怪——你需要在结构构造函数返回之前分配给每个字段。然而,结构体总是有一个编译器生成的无参数构造函数,它将所有字段初始化为它们的默认值。

因此,要么您的结构构造函数需要显式分配给每个字段(就像您的那样),要么您可以委托无参数构造函数将所有字段初始化为其默认值,然后只设置一些字段。

类的情况不同:您不需要在构造函数返回之前分配给每个字段。因此,您只能在具有显式无参数构造函数时调用 this(),并且您应该仅在出于某种原因想要显式调用该无参数构造函数时才调用它。

答案 2 :(得分:1)

在这种情况下,您的 Option<T> 毫无用处。但是您可以使用它来设置默认值 或计算值。

因此您可以创建这样的构造函数(来自 MS 文档):

this()

带有 public Employee(int weeklySalary, int numberOfWeeks) : this(weeklySalary * numberOfWeeks) { } public Employee(int annualSalary) { Salary = annualSalary; } 的 const 将调用第二个构造函数,以便设置 Salary。

如果您的代码如下所示,您必须在字段(或属性,如果有的话)前使用 this()

this