From base class in C#, get derived type?

前端 未结 2 1111
无人共我
无人共我 2021-02-02 05:21

Let\'s say we\'ve got these two classes:

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

public class Base
{
    protecte         


        
相关标签:
2条回答
  • 2021-02-02 05:43

    GetType() would give you what you're looking for.

    0 讨论(0)
  • 2021-02-02 05:54
    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
    
    0 讨论(0)
提交回复
热议问题