2010-10-29 53 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);