Link to an inheritance class from an abstract class

Is there a way to refer to a class (i.e. Type) that inherits an abstract class?

class abstract Monster
{
    string Weakness { get; }
    string Vice { get; }

    Type WhatIAm
    {
        get { /* somehow return the Vampire type here? */ }
    }
}

class Vampire : Monster
{
    string Weakness { get { return "sunlight"; }
    string Vice { get { return "drinks blood"; } }
}

//somewhere else in code...
Vampire dracula = new Vampire();
Type t = dracula.WhatIAm; // t = Vampire

For those who were interested ... what I'm doing: I want to know when my site was last published. .GetExecutingAssemblyworked fine until i pulled the dll out of my solution. After that, BuildDateit was always the last build date for the DLL utility, not the dll site.

namespace Web.BaseObjects
{
    public abstract class Global : HttpApplication
    {
        /// <summary>
        /// Gets the last build date of the website
        /// </summary>
        /// <remarks>This is the last write time of the website</remarks>
        /// <returns></returns>
        public DateTime BuildDate
        {
            get
            {
                // OLD (was also static)
                //return File.GetLastWriteTime(
                //    System.Reflection.Assembly.GetExecutingAssembly.Location);
                return File.GetLastWriteTime(
                    System.Reflection.Assembly.GetAssembly(this.GetType()).Location);
            }
        }
    }
}
+3
source share
4 answers

Use the method GetType(). It is virtual, so it will behave polymorphically.

Type WhatAmI {
  get { return this.GetType(); }
}
+7
source

, , . , , , Monster , . , .

+2

You do not need the Monster.WhatIAm property. C # has an "is" operator.

0
source

You can also get base class information directly from an inherited class ( Vampire) using the following snippet:

 Type type = this.GetType();     
 Console.WriteLine("\tBase class = " + type.BaseType.FullName);
0
source

Source: https://habr.com/ru/post/1772185/


All Articles