UFO ET IT

C #의 기본 클래스에서 파생 된 형식을 얻습니까?

ufoet 2020. 12. 29. 07:34
반응형

C #의 기본 클래스에서 파생 된 형식을 얻습니까?


다음 두 클래스가 있다고 가정 해 보겠습니다.

public class Derived : Base
{
    public Derived(string s)
        : base(s)
    { }
}

public class Base
{
    protected Base(string s)
    {

    }
}

생성자 내 에서 호출자 Base임을 어떻게 알 수 Derived있습니까? 이것이 내가 생각 해낸 것입니다.

public class Derived : Base
{
    public Derived(string s)
        : base(typeof(Derived), s)
    { }
}

public class Base
{
    protected Base(Type type, string s)
    {

    }
}

typeof(Derived)예를 들어 Base의 생성자 내에서 반사를 사용하는 방법과 같이 전달이 필요하지 않은 다른 방법이 있습니까?


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Base b = new Base();
            Derived1 d1 = new Derived1();
            Derived2 d2 = new Derived2();
            Base d3 = new Derived1();
            Base d4 = new Derived2();
            Console.ReadKey(true);
        }
    }

    class Base
    {
        public Base()
        {
            Console.WriteLine("Base Constructor. Calling type: {0}", this.GetType().Name);
        }
    }

    class Derived1 : Base { }
    class Derived2 : Base { }
}

이 프로그램은 다음을 출력합니다.

Base Constructor: Calling type: Base
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2
Base Constructor: Calling type: Derived1
Base Constructor: Calling type: Derived2

GetType() 당신이 찾고있는 것을 줄 것입니다.

참조 URL : https://stackoverflow.com/questions/972494/from-base-class-in-c-get-derived-type

반응형