Programing

C #의 기본 생성자-어느 것이 먼저 호출됩니까?

lottogame 2020. 7. 19. 09:51
반응형

C #의 기본 생성자-어느 것이 먼저 호출됩니까? [복제]


이 질문에는 이미 답변이 있습니다.

기본 생성자 또는 "여기 다른 것들"중 어느 것이 먼저 호출됩니까?

public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}

기본 생성자가 먼저 호출됩니다.

시도 해봐:

public class MyBase
{
  public MyBase()
  {
    Console.WriteLine("MyBase");
  }
}

public class MyDerived : MyBase
{
  public MyDerived():base()
  {
    Console.WriteLine("MyDerived");
  }
}

기본 클래스 생성자는 파생 클래스 생성자보다 먼저 호출되지만 파생 클래스 이니셜 라이저는 기본 클래스 이니셜 라이저보다 먼저 호출됩니다. 예를 들어 다음 코드에서 :

public class BaseClass {

    private string sentenceOne = null;  // A

    public BaseClass() {
        sentenceOne = "The quick brown fox";  // B
    }
}

public class SubClass : BaseClass {

    private string sentenceTwo = null; // C

    public SubClass() {
        sentenceTwo = "jumps over the lazy dog"; // D
    }
}

실행 순서는 C, A, B, D입니다.

이 2 msdn 기사를 확인하십시오.


그것을 기억하려고하지 말고, 무슨 일이 일어나고 있는지 설명해보십시오. Animal이라는 기본 클래스와 Dog라는 파생 클래스가 있다고 가정합니다. 파생 클래스는 기본 클래스에 일부 기능을 추가합니다. 따라서 파생 클래스의 생성자가 실행될 때 기본 클래스 인스턴스를 사용할 수 있어야합니다 (새 기능을 추가 할 수 있도록). 그래서 생성자는 기본에서 파생으로 실행되지만 소멸자는 반대 방식으로 실행됩니다. 먼저 파생 소멸자와 기본 소멸자입니다.

(이것은 단순화되었지만 실제로 이것을 암기 할 필요없이 미래 에이 질문에 대답하는 데 도움이 될 것입니다.)


실제로 파생 클래스 생성자가 먼저 실행되지만 C # 컴파일러는 파생 생성자의 첫 번째 문으로 기본 클래스 생성자에 대한 호출을 삽입합니다.

따라서 : 파생물이 먼저 실행되지만,베이스가 먼저 실행 된 것처럼 보입니다.


다른 사람들이 말했듯이 기본 생성자가 먼저 호출됩니다. 그러나 생성자가 실제로 가장 먼저 발생하는 것은 아닙니다.

다음과 같은 수업이 있다고 가정 해 봅시다.

class A {}

class B : A {}

class C : B {}

먼저, 필드 이니셜 라이저는 가장 파생 된 클래스부터 가장 파생 된 클래스 순서로 호출됩니다. 의 첫 번째 필드의 초기화 그래서 C다음, B다음 A.

생성자는 다음 반대의 순서로 호출됩니다 첫 번째 A의 생성자, 다음 B, 다음 C.


나는 기본이라고 말할 것이다

편집 참조 :

http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructorsInCS11122005010300AM/ConsNDestructorsInCS.aspx

거기에 말한다 :

using System;
class Base
{

public Base()
{
    Console.WriteLine("BASE 1");
}
public Base(int x)
{
    Console.WriteLine("BASE 2");
}
}

class Derived : Base
{
public Derived():base(10)
{
    Console.WriteLine("DERIVED CLASS");
}
}

class MyClient
{
public static void Main()
{
    Derived d1 = new Derived();
}
}

이 프로그램은 출력

BASE2

파생 클래스


Eric Lippert had an interesting post on the related issue of object initialization, which explains the reason for the ordering of constructors and field initializers:

Why Do Initializers Run In The Opposite Order As Constructors? Part One
Why Do Initializers Run In The Opposite Order As Constructors? Part Two


http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=777

Base Constructor gets called first.


The Exception Constructor will be called, then your Child class constructor will be called.

Simple OO principle

Have a look here http://www.dotnet-news.com/lien.aspx?ID=35151


Base Constructor is called first. But the initializer of fields in derived class is called first.

The calling order is

  1. derived class field initializer
  2. base class field initializer
  3. base class constructor
  4. derived class constructor

(You can treat 2 and 3 as a whole to construct the base class.)

Taken from CSharp Language Speification 5.0:

10.11.3 Constructor execution

Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed. Given the example

using System;
class A
{
    public A() {
        PrintFields();
    }
    public virtual void PrintFields() {}
}
class B: A
{
    int x = 1;
    int y;
    public B() {
        y = -1;
    }
    public override void PrintFields() {
        Console.WriteLine("x = {0}, y = {1}", x, y);
    }
}

when new B() is used to create an instance of B, the following output is produced:

x = 1, y = 0

The value of x is 1 because the variable initializer is executed before the base class instance constructor is invoked. However, the value of y is 0 (the default value of an int) because the assignment to y is not executed until after the base class constructor returns. It is useful to think of instance variable initializers and constructor initializers as statements that are automatically inserted before the constructor-body. The example

using System;
using System.Collections;
class A
{
    int x = 1, y = -1, count;
    public A() {
        count = 0;
    }
    public A(int n) {
        count = n;
    }
}
class B: A
{
    double sqrt2 = Math.Sqrt(2.0);
    ArrayList items = new ArrayList(100);
    int max;
    public B(): this(100) {
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        max = n;
    }
}

contains several variable initializers; it also contains constructor initializers of both forms (base and this). The example corresponds to the code shown below, where each comment indicates an automatically inserted statement (the syntax used for the automatically inserted constructor invocations isn’t valid, but merely serves to illustrate the mechanism).

using System.Collections;
class A
{
    int x, y, count;
    public A() {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = 0;
    }
    public A(int n) {
        x = 1;                                // Variable initializer
        y = -1;                               // Variable initializer
        object();                         // Invoke object() constructor
        count = n;
    }
}
class B: A
{
    double sqrt2;
    ArrayList items;
    int max;
    public B(): this(100) {
        B(100);                               // Invoke B(int) constructor
        items.Add("default");
    }
    public B(int n): base(n – 1) {
        sqrt2 = Math.Sqrt(2.0);           // Variable initializer
        items = new ArrayList(100);   // Variable initializer
        A(n – 1);                         // Invoke A(int) constructor
        max = n;
    }
}

The base constructor will be called first, otherwise, in cases where your "other stuff" must make use of member variables initialized by your base constructor, you'll get compile time errors because your class members will not have been initialized yet.


base(?) is called before any work is done in the child constructor.

This is true, even if you leave off the :base() (in which case, the 0-parameter base constructor is called.)

It works similar to java,

public Child()
{
   super(); // this line is always the first line in a child constructor even if you don't put it there! ***
}

*** Exception: I could put in super(1,2,3) instead. But if I don't put a call to super in explicitly, super() is called.


Constructor calls are called (fired) from the bottom up, and executed from the top down. Thus, if you had Class C which inherits from Class B which inherits from Class A, when you create an instance of class C the constructor for C is called, which in turn calls the instructor for B, which again in turn calls the constructor for A. Now the constructor for A is executed, then the constructor for B is executed, then the constructor for C is executed.

참고URL : https://stackoverflow.com/questions/140490/base-constructor-in-c-sharp-which-gets-called-first

반응형