【问题标题】:From base class in C#, get derived type?从 C# 中的基类,获取派生类型?
【发布时间】:2010-11-01 15:08:47
【问题描述】:

假设我们有这两个类:

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

【问题讨论】:

    标签: c# reflection inheritance types


    【解决方案1】:
    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();的输出
    • Derived1 d1 = new Base(); 会产生一个编译时错误,你的意思可能正好相反。仅供参考((Base)new Derived1()).GetType().Name 是“Derived1”
    【解决方案2】:

    GetType() 会给你你想要的东西。

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 2010-11-25
      • 2018-11-19
      • 1970-01-01
      • 2011-03-05
      • 2016-02-23
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多