从抽象类中引用继承类

3
有没有一种方法可以引用继承抽象类的类(即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个回答

7
使用GetType()方法。它是虚拟的,因此可以表现出多态性。
Type WhatAmI {
  get { return this.GetType(); }
}

2
或者更好的方法是,直接使用GetType()。 - Etienne de Martel
还要注意,GetType()将获取您使用的任何内容的实际类型,即使您已将其转换为其他内容(对于引用类型,当然是这样)。因此,如果您有一个像IMonster这样的接口,您可以使用IMonster.GetType()来查看它实际上是什么,同样适用于您的Monster抽象基类。 - CodexArcanum

2

看起来你只是想获取类型,上面两个答案都提供了很好的解决方案。从你提出问题的方式来看,我希望Monster没有任何依赖于Vampire的代码。那听起来像是违反依赖反转原则的例子,并会导致更加脆弱的代码。


1
这是我的第一想法,基类不应该知道继承类的类型。希望它不会在所有已知的子类中运行开关。如果是这样的话,依赖倒置原则就派上用场了。然而,似乎他只是想在基类中输出当前类型的方法,主要用于调试目的。我认为这很好,因为它不依赖于子类的行为。依赖倒置原则建议所有子类都应该定义一个getType方法。然而,基类已经定义了它,所以通过了依赖倒置原则的测试。 - Ruan Mendes

0

你也可以通过以下代码片段直接从继承类(Vampire)获取基类信息:

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

0

你不需要使用 Monster.WhatIAm 属性。C# 中有“is”运算符。


但我想要“返回”这个值,而不仅仅是比较它。 - Brad
为什么你需要返回它? - user490598
我添加了更多关于我正在做的事情。 - Brad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接