C #에서 추상 클래스의 생성자
C #에서 추상 클래스의 생성자를 작성할 수있는 이유는 무엇입니까?
내가 아는 한 우리는 추상 클래스를 인스턴스화 할 수 없습니다. 그래서 무엇을위한 것입니까?
수업을 인스턴스화 할 수 없습니다.
추상 클래스에서 데이터를 인스턴스화하려는 표준 방법이있을 수 있기 때문입니다. 이렇게하면 해당 클래스에서 상속 된 클래스가 기본 생성자를 호출하게 할 수 있습니다.
public abstract class A{
private string data;
protected A(string myString){
data = myString;
}
}
public class B : A {
B(string myString) : base(myString){}
}
내가 아는 한 추상 클래스를 인스턴스화 할 수 없다
거기에 오류가 있습니다. 물론 추상 클래스를 인스턴스화 할 수 있습니다.
abstract class Animal {}
class Giraffe : Animal {}
...
Animal animal = new Giraffe();
바로 거기에 Animal의 인스턴스가 있습니다. 구체적인 클래스를 파생 클래스에서 만들어 인스턴스화하여 추상 클래스를 인스턴스화합니다. 파생 된 콘크리트 클래스 의 인스턴스 도 추상 기본 클래스의 인스턴스입니다. 기린의 인스턴스는 동물이 추상적이더라도 동물의 인스턴스입니다.
추상 클래스를 인스턴스화 할 수 있다고 가정하면, 다른 클래스와 마찬가지로 생성자가 있어야 불변이 충족됩니다.
이제 정적 클래스는 실제로 인스턴스화 할 수없는 클래스이며 정적 클래스에서 인스턴스 생성자를 만드는 것이 합법적이지 않다는 것을 알 수 있습니다.
추상 클래스의 변형을 적용하는 방법입니다. 즉, 서브 클래스가 무엇을하든 항상 어떤 것이 기본 클래스에 해당되는지 확인하려고합니다 ... 예 :
abstract class Foo
{
public DateTime TimeCreated {get; private set;}
protected Foo()
{
this.TimeCreated = DateTime.Now;
}
}
abstract class Bar : Foo
{
public Bar() : base() //Bar's constructor's must call Foo's parameterless constructor.
{ }
}
생성자를 new
연산자 의 이중으로 생각하지 마십시오 . 생성자의 유일한 목적은 객체를 사용하기 전에 유효한 상태에 있는지 확인하는 것입니다. 단지 우리가 보통new
연산자를 통해 호출 한다는 것 입니다.
추상 클래스의 모든 구현 또는 추상 클래스에서 구현 한 모든 메소드에 필요한 일부 초기화 논리를 적용해야합니다 (추상 클래스의 모든 메소드가 추상적 일 필요는 없으며 일부는 구현 될 수 있음).
추상 기본 클래스에서 상속 된 모든 클래스는 기본 생성자를 호출해야합니다.
일반적으로 생성자는 생성되는 객체의 멤버를 초기화합니다. 상속 개념에서 상속 계층 구조의 각 클래스 생성자는 고유 한 멤버 변수를 인스턴스화해야합니다. 변수가 정의 된 곳에서 인스턴스화를 수행해야하기 때문에 이치에 맞습니다.
추상 클래스는 완전히 추상적이지 않기 때문에 (인터페이스와 달리) 추상 멤버와 구체적인 멤버가 혼합되어 있으며 추상 클래스가 아닌 멤버를 초기화해야하며 추상 클래스의 생성자에서 수행되므로 생성자가 있어야합니다. 추상 클래스에서. 물론 추상 클래스의 생성자는 파생 클래스의 생성자에서만 호출 할 수 있습니다.
모든 메소드를 구현 한 후이를 인스턴스화 할 수 있습니다. 그런 다음 생성자가 호출됩니다.
I too want to make some shine on abstract surface All answer has covered almost all the things. Still my 2 cents
abstract classes are normal classes with A few exceptions
- You any client/Consumer of that class can't create object of that class, It never means that It's constructor will never call. Its derived class can choose which constructor to call.(as depicted in some answer)
- It may has abstract function.
Defining a constructor with public or internal storage class in an inheritable concrete class Thing
effectively defines two methods:
A method (which I'll call
InitializeThing
) which acts uponthis
, has no return value, and can only be called fromThing
'sCreateThing
andInitializeThing
methods, and subclasses'InitializeXXX
methods.A method (which I'll call
CreateThing
) which returns an object of the constructor's designated type, and essentially behaves as:Thing CreateThing(int whatever) { Thing result = AllocateObject<Thing>(); Thing.initializeThing(whatever); }
Abstract classes effectively create methods of only the first form. Conceptually, there's no reason why the two "methods" described above should need to have the same access specifiers; in practice, however, there's no way to specify their accessibility differently. Note that in terms of actual implementation, at least in .NET, CreateThing
isn't really implemented as a callable method, but instead represents a code sequence which gets inserted at a newThing = new Thing(23);
statement.
an abstract class can have member variables that needs to be initialized,so they can be initialized in the abstract class constructor and this constructor is called when derived class object is initialized.
From https://msdn.microsoft.com/en-us/library/ms182126.aspx
Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type, and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.
Since only derived classes can use an abstract class constructor then an abstract class constructor, if needed, must be declared as protected
.
However, that said VS compiler will not complain (with default rules) when declaring public constructors in abstract classes however it will not allow creating a new instance.
You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.
There are two following important features that prevent to inherit Abstract class
Abstract class must have an abstract method otherwise it is not a abstract class
Abstract class must be inherited by derived class,So if a class inherited by other class than what is use of to create object of that class
참고URL : https://stackoverflow.com/questions/5601777/constructor-of-an-abstract-class-in-c-sharp
'IT' 카테고리의 다른 글
현재 경로 이름을 얻는 방법? (0) | 2020.05.12 |
---|---|
Visual Studio 2010은 항상 프로젝트가 오래되었다고 생각하지만 아무것도 변경되지 않았습니다. (0) | 2020.05.12 |
JavaScript 오류 (Uncaught SyntaxError : 예기치 않은 입력 끝) (0) | 2020.05.12 |
HTTP 오류 500.19 및 오류 코드 : 0x80070021 (0) | 2020.05.12 |
서버 측 확장을 빌드하려면 postgresql-server-dev-XY를 설치하고 클라이언트 측 애플리케이션을 빌드하려면 libpq-dev를 설치해야합니다. (0) | 2020.05.12 |