2008-12-03 116 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);}