从C#中的基类获取派生类型?

87

假设我们有这两个类:

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 的构造函数中使用反射的方式?

2个回答

126
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

一个更好的例子是展示 Derived1 d1 = new Base(); 的输出结果。 - Seph
6
"Derived1 d1 = new Base();" 这句话会产生一个编译时错误,你可能是想表达相反的意思。FYI,"((Base)new Derived1()).GetType().Name" 的结果是 "Derived1"。 - M.Stramm

42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接