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


70

假设我们有以下两个类:

public class Derived : Base
{
    public Derived(string s)
        : base(s)
    { }
}

public class Base
{
    protected Base(string s)
    {

    }
}

我怎样才能从内部的构造函数中找出BaseDerived是调用?这是我想出的:

public class Derived : Base
{
    public Derived(string s)
        : base(typeof(Derived), s)
    { }
}

public class Base
{
    protected Base(Type type, string s)
    {

    }
}

还有另一种不需要传递的方法typeof(Derived),例如,某种使用Base构造函数中的反射的方法吗?

Answers:


109
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 2012年

6
Derived1 d1 = new Base();生成一个编译时错误,您可能反过来。仅供参考((Base)new Derived1()).GetType().Name:“衍生1”
M.Stramm

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.