假设我们有这两个类:
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
的构造函数中使用反射?
答案 0 :(得分:91)
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
答案 1 :(得分:31)
GetType()
会给你你想要的东西。