开发者

Reference the inherting class from the abstract class

Is there a way to reference the class (i.e. Type) that inherits a 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 curious... what I'm doing: I want to know when my website was last published. .GetExecutingAssembly worked perfectly until I took the dll out of my solution. After that, the BuildDate was always the last build date of the utility dll, not the website's dll.

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);
            }
        }
    }
}


Use the GetType() method. It's virtual so it will behave polymorphically.

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


Looks like you're just looking to get the type, which both of the above answers provide well. From the way you asked the question, I hope Monster doesn't have any code that depends on Vampire. That sounds like it would be an example of a violation of the Dependency Inversion Principle, and lead to more brittle code.


You don't need the Monster.WhatIAm property. C# has the "is" operator.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜