代码之家  ›  专栏  ›  技术社区  ›  Brad

从抽象类引用inherting类

  •  3
  • Brad  · 技术社区  · 14 年前

    Type )继承抽象类的?

    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
    

    对于那些好奇的人。。。 我在做什么:我想知道我的网站最后一次发布是什么时候。 .GetExecutingAssembly 工作得很好,直到我把dll从我的解决方案中取出。在那之后 BuildDate 始终是实用程序dll的最后生成日期,而不是网站的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);
                }
            }
        }
    }
    
    4 回复  |  直到 14 年前
        1
  •  7
  •   JaredPar    14 年前

    使用 GetType() 方法。它是虚拟的,所以它会表现出多态性。

    Type WhatAmI {
      get { return this.GetType(); }
    }
    
        2
  •  2
  •   Visionary Software Solutions    14 年前

    Dependency Inversion Principle ,并导致更脆弱的代码。

        3
  •  0
  •   Matthew Graybosch    14 年前

    你不需要怪物。什么东西。C有“is”接线员。

        4
  •  0
  •   rkg    14 年前

    Vampire )使用以下代码段:

     Type type = this.GetType();     
     Console.WriteLine("\tBase class = " + type.BaseType.FullName);
    
    推荐文章