Nice programing

base () 및 this () 생성자 모범 사례

nicepro 2020. 10. 11. 11:20
반응형

base () 및 this () 생성자 모범 사례


어떤 조건에서 생성자의 괄호를 따라 :base():this()생성자를 호출 해야합니다 (또는 코드의 다른 위치에서도). 이러한 통화의 모범 사례는 언제이며 언제 필수입니까?


: base(...)

기본 생성자에 대한 호출을 생략하면 기본 생성자를 자동으로 호출합니다.

기본 생성자가없는 경우 기본 생성자를 명시 적으로 호출해야합니다.

기본 생성자가 있더라도 기본 생성자와 다른 생성자를 호출 할 수 있습니다. 이 경우에도 base(foo, bar)기본 생성자와 다른 생성자를 호출하는 데 사용할 수 있습니다 .

base()기본 클래스 기본 생성자를 호출 할 때 생략하는 것이 나쁜 관행이라고 생각하지 않지만 명시 적으로 지정하고 싶다면 포함해도 해가되지 않습니다. 맛의 문제입니다.

: this(...)

이 구문을 사용하면 동일한 클래스 내에서 다른 서명과 다른 서명을 사용하여 하나의 생성자를 호출 할 수 있습니다. 이 작업을 반드시 수행해야하는 것은 아니지만 때때로 유용 할 수 있습니다.

유용 할 수있는 경우의 예는 생성자에서 공통 코드를 재사용하는 것입니다. 예를 들어 C # 3.5 이전에서는 생성자에서 선택적 매개 변수를 시뮬레이션 할 수 있습니다.

Foo(int x, int y)
{
     this.x = x;
     this.y = y;
}

Foo(int x) : this(x, 10) {}  // y defaults to 10

C # 4.0에서는 이제 이러한 접근 방식의 필요성을 줄여주는 선택적 매개 변수를 사용할 수 있습니다.

생성자에서 코드를 재사용하는 또 다른 방법은 코드를 사용하려는 각 생성자에서 호출되는 정적 함수로 분해하는 것입니다.


우선, 그들이 의무적 일 때.

클래스가되면 Derived클래스에서 파생 Base하고, Base기본 (매개 변수없는) 생성자가없는, Derived호출해야 base()매개 변수를 명시 적으로.

public class Base {
    public Base(int i) { }
}


public class Derived : Base {
    // public Derived() { } wouldn't work - what should be given for i?
    public Derived() : base(7) { }
    public Derived(int i) : base(i) { }
}

좋은 습관은 언제입니까? 다른 생성자를 호출 할 때마다.

이전 예제에서 Derived의 생성자에 콘텐츠를 추가한다고 가정합니다.

public class Derived : Base {
    // public Derived() { } wouldn't work - what should be given for i?
    public Derived() : base(7) {
        Console.WriteLine("The value is " + 7);
    }
    public Derived(int i) : base(i) {
        Console.WriteLine("The value is " + i);
    }
}

여기서 중복 된 것을 보셨나요? this () 생성자를 호출하는 것이 더 간단합니다.

public class Derived : Base {
    // public Derived() { } wouldn't work - what should be given for i?
    public Derived() : this(7) { }
    public Derived(int i) : base(i) {
        Console.WriteLine("The value is " + i);
    }
}

base상속이 있고 부모 클래스가 이미 달성하려는 기능을 제공 할 때 사용 합니다.

사용은 this이미 다른 생성자에 정의 된 기능을 복제하지 않으려 할 때 현재의 엔티티 (또는 자체)를 참조 할 때, 생성자의 헤더 / 서명에 사용합니다.

기본적으로 생성자의 헤더에서 base와 this를 사용하는 것은 코드를 DRY 유지하여 유지 관리가 쉽고 장황하지 않게 만드는 것입니다.

여기에 절대적으로 무의미한 예가 있지만 두 가지가 어떻게 사용될 수 있는지 보여주는 아이디어를 보여줍니다.

class Person
{
    public Person(string name)
    {
        Debug.WriteLine("My name is " + name);
    }
}

class Employee : Person
{
    public Employee(string name, string job)
        : base(name)
    {
        Debug.WriteLine("I " + job + " for money.");
    }

    public Employee() : this("Jeff", "write code")
    {
        Debug.WriteLine("I like cake.");
    }
}

용법:

var foo = new Person("ANaimi");
// output:
//  My name is ANaimi

var bar = new Employee("ANaimi", "cook food");
// output:
//  My name is ANaimi
//  I cook food for money.

var baz = new Employee();
// output:
//  My name is Jeff
//  I write code for money.
//  I like cake.

"C #의 생성자 체인"을 찾습니다. 기본적으로 다음과 같습니다.

MyClass():base()  //default constructor calling superclass constructor
{
}

MyClass(int arg):this()  //non-basic constructor calling base constructor
{
    //extra initialization
}

생성자에서 코드 중복을 제거하는 데 도움이됩니다. 기본 및 특정 부분으로 분할합니다.


기본 클래스의 생성자가 생성자의 첫 번째 명령어로 자동 호출되도록하려면 : base ()를 사용합니다. : this () 비슷하지만 같은 클래스에서 다른 생성자를 호출합니다.

base :() 및 this () : 매개 변수 상수 값 또는 생성자의 매개 변수를 기반으로하는 표현식으로 전달할 수 있습니다.

It's mandatory to call the base constructor when the base class has no default constructor (one that takes no parameters). I don't know of a case in which :this() is mandatory.

public class ABaseClass
{
    public ABaseClass(string s) {}
}

public class Foo : AChildClass
{
    public AChildClass(string s) : base(s) {} //base mandatory
    public AChildClass() : base("default value") {}  //base mandatory
    public AChildClass(string s,int i) : base(s+i) {}  //base mandatory
}

public class AnotherBaseClass
{
    public ABaseClass(string s) {}
    public ABaseClass():this("default value") {} //call constructor above
}

public class Foo : AnotherChildClass
{
    public AnotherChildClass(string s) : base(s) {} //base optional

}

참고URL : https://stackoverflow.com/questions/3797528/base-and-this-constructors-best-practices

반응형