简体   繁体   中英

C# how to check if base class is instance of derived class

How to check from within the base class if it is an instance of a derived class:

class A0 : A {};
class A1 : A {};
class A2 : A {};

class A 
{
    void CheckDerived() 
    {
        if (this is A0) 
        {
            //Do something when instance is A0
        } 
        else if (this is A1) 
        {
            //Do something when instance is A1
        } 
        else if (this is A2) 
        {
            //Do something when instance is A2
        }
    }
}

The code in the question should do what you want, however, as Danny Goodball wrote in his comment, this is a very bad practice.

According to the open/close principle , stating that "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification",
The proper way to handle different actions for different children is using override:

Make the method virtual (might be even better as an abstract method), and override it in each derived class with it's own implementation:

class A
{
     virtual void CheckDerived() { throw new NotImplementedException(); }
}

class A0 : A
{
     void override CheckDerived() { Console.WriteLine("A0"); }
}

class A1 : A
{
     void override CheckDerived() { Console.WriteLine("A1"); }
}

you should do this using class types and IsAssignableFrom method

  public class Program
{
public static void Main()
{
    A a = new A0();
    a.CheckDerived();

 }
}

class A0 : A {};
class A1 : A {};
class A2 : A {};
class A {
public void CheckDerived() {
    if(this.GetType().IsAssignableFrom(typeof(A0))) Console.Write("A0");
    if(this.GetType().IsAssignableFrom(typeof(A1))) Console.Write("A1");
    if(this.GetType().IsAssignableFrom(typeof(A2))) Console.Write("A2");
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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