2010-10-29 55 views
3

有没有办法引用继承抽象类的类(即Type)?引用抽象类中的inherting类

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

回答

7

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

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

或者,更好的,只是用gettype()。 – 2010-10-29 20:20:25

+0

还要注意,GetType()将获得您正在使用的任何类型的实际类型,即使您已将其转换为其他类型(当然也适用于参考类型)。所以如果你有像IMonster这样的接口,你可以使用IMonster.GetType()来查看它的实际内容,同样也适用于你的Monster抽象基础。 – CodexArcanum 2010-10-29 20:25:43

0

你不需要Monster.WhatIAm财产。 C#拥有“is”运算符。

+0

但我想'返回'的价值,而不是简单地比较它。 – Brad 2010-10-29 20:21:58

+0

你为什么需要退货? – 2010-10-29 20:23:26

+0

我加了更多关于我在做什么 – Brad 2010-10-29 20:36:09

2

看起来你只是想找到类型,这两个答案都很好。从你问这个问题的方式来说,我希望怪物没有任何依赖吸血鬼的代码。这听起来像是一个违反Dependency Inversion Principle的例子,并导致更脆弱的代码。

+1

这是我第一次想到,基类应该永远不需要知道继承类的类型。希望它不会在所有已知的子类上运行切换。如果这就是发生的事情,DIP是你的朋友。然而,他似乎只是想在输出当前类型的基类中使用一种方法,主要是为了调试目的。听起来不错,因为它不依赖于子类的行为。 DIP会建议所有的子类都应该定义一个getType方法。但是基类已经定义了它,所以通过了DIP测试。 – 2010-10-29 20:41:30

0

您也可以直接使用下面的代码片断继承类(Vampire)得到的基类信息:

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