在 C# 构造函数中使用 this() [英] Using this() in C# Constructors

查看:28
本文介绍了在 C# 构造函数中使用 this()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚这些构造函数之间是否存在任何差异.假设有一个不带参数的 Foo() 构造函数,所有这些构造函数都会有相同的结果吗?

I have been trying to figure out if there are any differences between these constructors. Assuming there is a Foo() constructor that takes no arguments, are all these constructors going to have the same result?

public Foo()
    : this()
{
     blah;
     blah;
     blah;
}

示例 2

public Foo()
{
     this();
     blah;
     blah;
     blah;
}

示例 3

public Foo()
{
     this = new Foo();
     blah;
     blah;
     blah;
}

推荐答案

  • 示例 1 是有效的(假设有一个无参数构造函数),并且调用无参数构造函数作为初始化的一部分.有关更多详细信息,请参阅我的关于构造函数链的文章.请注意,由于 OP 的编辑,它是无限递归的.
  • 示例 2 永远无效
  • 示例 3 仅在 Foo 是结构体时有效,并且没有做任何有用的事情.
    • Example 1 is valid (assuming there is a parameterless constructor), and calls the parameterless constructor as part of initialization. See my article on constructor chaining for more details. Note that since the OP's edit, it's infinitely recursive.
    • Example 2 is never valid
    • Example 3 is only valid when Foo is a struct, and doesn't do anything useful.
    • 我会避免在结构中分配给 this.正如您从其他答案中看到的那样,它的 可能性 很少为人所知(我只知道是因为它出现在规范中的一些奇怪情况).在你得到它的地方,它没有任何好处 - 在其他地方,它可能会改变结构,这不是一个好主意.结构应该始终是不可变的 :)

      I would steer clear of assigning to this in structs. As you can see from the other answers, the very possibility of it is fairly rarely known (I only know because of some weird situation where it turned up in the spec). Where you've got it, it doesn't do any good - and in other places it's likely to be mutating the struct, which is not a good idea. Structs should always be immutable :)

      只是为了让人们meep!"有点 - 分配给 this 与链接到另一个构造函数并不完全相同,因为您也可以在方法中进行:

      Just to make people go "meep!" a little - assigning to this isn't quite the same as just chaining to another constructor, as you can do it in methods too:

      using System;
      
      public struct Foo
      {
          // Readonly, so must be immutable, right?
          public readonly string x;
      
          public Foo(string x)
          {
              this.x = x;
          }
      
          public void EvilEvilEvil()
          {
              this = new Foo();
          }
      }
      
      public class Test
      {
          static void Main()
          {
              Foo foo = new Foo("Test");
              Console.WriteLine(foo.x); // Prints "Test"
              foo.EvilEvilEvil();
              Console.WriteLine(foo.x); // Prints nothing
          }
      }
      

      这篇关于在 C# 构造函数中使用 this()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆