Per Erik Strandberg /cv /kurser /blog

I wanted to know if you can check if an inherited class is an instance of its parent class. The following little example illustrates how to do it:

using System;
using System.Collections.Generic;
using System.Text;

namespace Arv
{
  public interface IFordon { }
  public interface IMotorFordon : IFordon { }
  public class TvåHjuling { }
  public class MotorCykel : TvåHjuling, IMotorFordon { }
  public class MotorCykelMedSidoVagn : MotorCykel { }

  class Arv
  {
    static void Main(string[] args)
    {
      MotorCykelMedSidoVagn Harley = new MotorCykelMedSidoVagn();

      Console.WriteLine("'Harley is a IMotorFordon' is {0}.", Harley.GetType() == typeof(IMotorFordon));
      Console.WriteLine("'Harley is a TvåHjuling'   is {0}.", Harley.GetType() == typeof(TvåHjuling));
      Console.WriteLine("'Harley is a MotorCykel'   is {0}.", Harley.GetType() == typeof(MotorCykel));

      Console.WriteLine("'MotorCykelMedSidoVagn is a subclass of IMotorFordon' is {0}.", Harley.GetType().IsSubclassOf(typeof(IMotorFordon)));
      Console.WriteLine("'MotorCykelMedSidoVagn is a subclass of TvåHjuling'   is {0}.", Harley.GetType().IsSubclassOf(typeof(TvåHjuling)));
      Console.WriteLine("'MotorCykelMedSidoVagn is a subclass of MotorCykel'   is {0}.", Harley.GetType().IsSubclassOf(typeof(MotorCykel)));

      foreach (System.Type T in Harley.GetType().GetInterfaces())
        Console.WriteLine("Harley implements the interface '{0}'", T);

    }
  }
}

The output should be something like this:

'Harley is a IMotorFordon' is False.
'Harley is a TvåHjuling'   is False.
'Harley is a MotorCykel'   is False.
'MotorCykelMedSidoVagn is a subclass of IMotorFordon' is False.
'MotorCykelMedSidoVagn is a subclass of TvåHjuling'   is True.
'MotorCykelMedSidoVagn is a subclass of MotorCykel'   is True.
Harley implements the interface 'Arv.IMotorFordon'
Harley implements the interface 'Arv.IFordon'


This page is a member of Kategori Programmering.