2008-12-03 120 views
3

好吧,我有以下結構。基本上是一個插件架構如何獲得類的名稱

// assembly 1 - Base Class which contains the contract 
public class BaseEntity { 
    public string MyName() { 
    // figure out the name of the deriving class 
    // perhaps via reflection 
    } 
} 

// assembly 2 - contains plugins based on the Base Class 
public class BlueEntity : BaseEntity {} 
public class YellowEntity : BaseEntity {} 
public class GreenEntity : BaseEntity {} 


// main console app 
List<BaseEntity> plugins = Factory.GetMePluginList(); 

foreach (BaseEntity be in plugins) { 
    Console.WriteLine(be.MyName); 
} 

我想聲明

be.MyName 

告訴我對象是BlueEntity,YellowEntity或GreenEntity。重要的是MyName屬性應該在基類中,因爲我不想在每個插件中重新實現屬性。

這是可能的C#?

回答

10

我想你可以通過的GetType做到這一點:

public class BaseEntity { 
    public string MyName() { 
     return this.GetType().Name 
    } 
} 
-2

嘗試這種模式

class BaseEntity { 
    private readonly m_name as string; 
    public Name { get { return m_name; } } 
    protected BaseEntity(name as string) { 
    m_name = name; 
    } 
} 
class BlueEntity : BaseEntity { 
    public BlueEntity() : base(typeof(BlueEntity).Name) {} 
} 
+0

這不正是提問是尋找(看看他添加到MyName方法中的註釋問題) – hhafez 2008-12-03 23:00:20

1

更改您的foreach語句下面

foreach (BaseEntity be in plugins) { 
    Console.WriteLine(be.GetType().Name); 
} 
2

C#實現的方式來看待在名爲反射的對象。這可以返回有關您正在使用的對象的信息。

GetType()函數返回您正在調用它的類的名稱。你可以這樣使用它:

return MyObject.GetType().Name; 

反射可以做很多事情。如果有更多的,你想了解反射,你可以在這些網站上讀到它:

5
public class BaseEntity { 
    public string MyName() { 
    return this.GetType().Name; 
    } 
} 

「這個」 將指向派生類,所以如果你這樣做:

BaseEntity.MyName 
"BaseEntity" 

BlueEntitiy.MyName 
"BlueEntity" 

編輯:Doh,高爾基打敗了我。

-1

如果您還沒有覆蓋的ToString()方法的類,那麼你可以像下面

string s = ToString().Split(',')[0]; // to get fully qualified class name... or, 
s = s.Substring(s.LastIndexOf(".")+1); // to get just the actual class name itself 

使用歲代碼:

// assembly 1 - Base Class which contains the contractpublic class BaseEntity 
    { 
     public virtual string MyName // I changed to a property 
     {  
      get { return MyFullyQualifiedName.Substring(
       MyFullyQualifiedName.LastIndexOf(".")+1); } 
     } 
     public virtual string MyFullyQualifiedName // I changed to a property 
     {  
      get { return ToString().Split(',')[0]; } 
     } 
} 
// assembly 2 - contains plugins based on the Base Class 
public class BlueEntity : BaseEntity {} 
public class YellowEntity : BaseEntity {} 
public class GreenEntity : BaseEntity {} 
// main console app 
    List<BaseEntity> plugins = Factory.GetMePluginList(); 
    foreach (BaseEntity be in plugins) 
    { Console.WriteLine(be.MyName);} 
相關問題