C#类的解构器会删除/销毁内存中的类吗?

huangapple go评论50阅读模式
英文:

Do c# class deconstructors delete/destroy the class from memory?

问题

我正在阅读关于 c# 10 的内容,并阅读到以下内容:

>"解构器(也称为解构方法)作为构造器的近似反义词:构造器通常接受一组值(作为参数)并将它们分配给字段,而解构器则相反,将字段分配回一组变量。"

我理解这可以用于获取类中的一堆成员值,但它是否会影响类的生命周期呢?也就是说,它是否会强制删除对它的所有引用,并进行垃圾回收,还是只会返回值?

英文:

Im reading about c# 10 and read

>"A deconstructor (also called a deconstructing method) acts as an approximate
opposite to a constructor: whereas a constructor typically takes a set of values (as
parameters) and assigns them to fields, a deconstructor does the reverse and assigns
fields back to a set of variables."

I get that this can be used to get a bunch of member values in a class, but does it do anything regarding the life cycle of the class? As in does it force all references to it to be removed and for it to be garbage collected or does it just return values?

答案1

得分: 5

DeconstructorDestructor 不同(C#根本没有它们),deconstructor 不处理内存分配;deconstructor 仅仅是一种 语法糖,通常只分配 out 参数,没有其他操作,例如:

public class MyClass {
  public MyClass(int a, int b, int c) {
    A = a;
    B = b;
    C = c;
  }

  public int A { get; }

  public int B { get; }

  public int C { get; }

  // Deconstructor什么也不做,只是分配out参数
  public void Deconstruct(out int a, out int b, out int c) {
    a = A;
    b = B;
    c = C;
  }
}

然后,你可以这样使用:

MyClass test = new MyClass(1, 2, 3);

...

// Deconstructor使代码更易读
(int a, int b, int c) = test;

而不是:

MyClass test = new MyClass(1, 2, 3);

...

int a = test.A;
int b = test.B;
int c = test.C;
英文:

Deconstructor unlike Destructor (c# doesn't have them at all) doesn't do anything with memory allocation; deconstructor is just
a syntactic sugar, it usually assigns out parameters and nothing more e.g.

    public class MyClass {
      public MyClass(int a, int b, int c) {
        A = a;
        B = b;
        C = c;
      }

      public int A { get; }

      public int B { get; }

      public int C { get; }

      // Deconstructor does nothing but assigns out parameters
      public void Deconstruct(out int a, out int b, out int c) {
        a = A;
        b = B;
        c = C;
      }
    }

then you can put

    MyClass test = new MyClass(1, 2, 3);

    ...

    // Deconstructor makes code easier to read
    (int a, int b, int c) = test;

instead of

    MyClass test = new MyClass(1, 2, 3);

    ...

    int a = test.A;
    int b = test.B;
    int c = test.C;

huangapple
  • 本文由 发表于 2023年6月19日 03:35:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502246.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定