반응형
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
반응형
'UFO ET IT' 카테고리의 다른 글
JSON 경로에 특정 요소가 포함되어 있지 않거나 요소가 존재하는지 여부를 테스트하는 방법은 null입니까? (0) | 2020.12.29 |
---|---|
원격 컴퓨터에서 서비스를 다시 시작하는 가장 간단한 방법 (0) | 2020.12.29 |
Windows에 권장하는 HTTP 트래픽 모니터는 무엇입니까? (0) | 2020.12.29 |
C에서 문자열을 연결하면 어떤 방법이 더 효율적입니까? (0) | 2020.12.29 |
* .o 파일이란? (0) | 2020.12.29 |