Program Tip

항상 클래스에 기본 생성자를 포함해야합니까?

programtip 2020. 11. 10. 22:09
반응형

항상 클래스에 기본 생성자를 포함해야합니까?


클래스에 항상 기본 생성자를 포함해야하는 동료로부터이 질문을 받았습니다. 그렇다면 그 이유는 무엇입니까? 아니라면 왜 안됩니까?

public class Foo {

    Foo() { }

    Foo(int x, int y) {
        ...
    } 

}

나는 또한 전문가로부터 이것에 대한 몇 가지 조명을 얻는 데 관심이 있습니다.


오버로드 된 생성자를 제공하지 않으면 컴파일러가 기본 생성자를 생성한다는 점을 명심해야합니다. 즉,

public class Foo
{ 
} 

컴파일러는 이것을 다음과 같이 생성합니다.

public class Foo
{ 
    public Foo() { }  
} 

그러나 다른 생성자를 추가하자마자

public class Foo
{ 
    public Foo(int x, int y)
    { 
        // ... 
    }  
} 

컴파일러는 더 이상 기본 생성자를 자동으로 생성하지 않습니다. 클래스가 기본 생성자의 존재에 의존하는 다른 코드에서 이미 사용중인 경우 Foo f = new Foo();해당 코드는 이제 중단됩니다.

다른 사람이 데이터를 제공하지 않고 클래스를 초기화 할 수 private없도록하려면 입력 데이터없이 인스턴스가 생성되는 것을 방지한다는 사실을 명시 하는 기본 생성자를 만들어야합니다 .

그러나 기본 생성자 (공개 또는 개인)를 제공해야하는 경우가 있습니다. 앞서 언급했듯이 일부 직렬화 유형에는 기본 생성자가 필요합니다. 클래스에 매개 변수화 된 생성자가 여러 개 있지만 "낮은 수준"초기화가 필요한 경우도 있습니다.이 경우 매개 변수화 된 생성자에서 연결된 개인 기본 생성자를 사용할 수 있습니다.

public class Foo
{
   private Foo()
   {
      // do some low level initialization here
   }

   public Foo(int x, int y)
      : this()
   {
      // ...
   }

   public Foo(int x, int y, int z)
      : this()
   {
      // ...
   }
}

직렬화와 같은 일부 항목에는 기본 생성자가 필요합니다. 그러나 그 외에 기본 생성자는 의미가있는 경우에만 추가해야합니다.

For example, if the Foo.X and Foo.Y properties are immutable after construction then a default constructor doesn't really make sense. Even if it were to used for an 'empty' Foo, a static Empty accessor would be more discoverable.


I would say no, definitely not always. Suppose you have a class with some readonly fields that must be initialized to some value, and there are no reasonable defaults (or you don't want there to be)? In this scenario I don't think a parameterless constructor makes sense.


Having a default constructor is only a good idea if it makes sense to have such an object.

If you produce an object which is not in a valid state from such a constructor, then the only thing it can do is introduce a bug.


As a side note, when using struct instead of class, note that there are no way to leave the default constructor out, nor is it possible to define it yourself, so regardless of which constructors you define, make sure that the default state of the struct (when all variables are set to their default state (usually 0 for value types, and null for reference types) won't break your implementation of the struct.


Yes It is better to have a default constructor in place to ensure you avoid any confusion. I have seen people just do nothing inside a default constructor (even in Microsoft's own classes) but still like to keep it as objects do get default(type) automatically. The classes which does not specify default constructor, .NET will automatically add them for you.

Serialization needs Default constructor if you use existing serializers as it makes sense for general purpose serializers, otherwise you need to create your own implementation.


In most cases a default constructor is a good idea. But since you use the word "always", all that's needed is one counterexample. If you look at the Framework, you'll find plenty. For example, System.Web.HttpContext.


A generic type can only be instantiated with C# means (without reflection) if it has a default constructor. Also, the new() generic type constraint has to be specified:

void Construct<T>()
    where T : new()
{
    var t = new T();
    ...
}

Calling this method using a type as generic type argument that has no default constructor results in a compiler error.

참고URL : https://stackoverflow.com/questions/3692042/should-we-always-include-a-default-constructor-in-the-class

반응형