如何获取类的名称

Ang*_*ker 3 c# visual-studio-2008

好的,我有以下结构.基本上是一个插件架构

// 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);
}
Run Code Online (Sandbox Code Playgroud)

我想要这个声明

be.MyName
Run Code Online (Sandbox Code Playgroud)

告诉我对象是BlueEntity,YellowEntity还是GreenEntity.重要的是MyName属性应该在基类中,因为我不想在每个插件中重新实现该属性.

这可能在C#中吗?

Gro*_*kys 10

我想你可以通过GetType来做到这一点:

public class BaseEntity {
    public string MyName() {
        return this.GetType().Name
    }
}
Run Code Online (Sandbox Code Playgroud)


Fly*_*wat 5

public class BaseEntity {
  public string MyName() {
     return this.GetType().Name;
  }
}
Run Code Online (Sandbox Code Playgroud)

"this"将指向派生类,所以如果你这样做:

BaseEntity.MyName
"BaseEntity"

BlueEntitiy.MyName
"BlueEntity"
Run Code Online (Sandbox Code Playgroud)

编辑:Doh,高尔基打败了我.