好的,我有以下结构.基本上是一个插件架构
// 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 Listplugins = Factory.GetMePluginList(); foreach (BaseEntity be in plugins) { Console.WriteLine(be.MyName); }
我想要这个声明
be.MyName
告诉我对象是BlueEntity,YellowEntity还是GreenEntity.重要的是MyName属性应该在基类中,因为我不想在每个插件中重新实现该属性.
这可能在C#中吗?
我想你可以通过GetType来做到这一点:
public class BaseEntity { public string MyName() { return this.GetType().Name } }
public class BaseEntity { public string MyName() { return this.GetType().Name; } }
"this"将指向派生类,所以如果你这样做:
BaseEntity.MyName "BaseEntity" BlueEntitiy.MyName "BlueEntity"
编辑:Doh,高尔基打败了我.