简体   繁体   English

从C#中的基类,得到派生类型?

[英]From base class in C#, get derived type?

Let's say we've got these two classes: 假设我们有这两个类:

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

public class Base
{
    protected Base(string s)
    {

    }
}

How can I find out from within the constructor of Base that Derived is the invoker? 如何从Base的构造函数中找出Derived是调用者? This is what I came up with: 这就是我想出的:

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

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

    }
}

Is there another way that doesn't require passing typeof(Derived) , for example, some way of using reflection from within Base 's constructor? 是否有另一种方法不需要传递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 { }
}

This program outputs the following: 该程序输出以下内容:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM