[英]From base class in C#, get derived type?
假設我們有這兩個類:
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()
會給你你想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.