从C#中的基类,获得派生types?
假设我们有这两个类:
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
的构造函数中使用reflection的一些方法?
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()
会给你你想要的。