如何获取类的名称

时间:2008-12-03 18:42:37

标签: 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);
}

我想要声明

be.MyName

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

这在C#中是否可行?

6 个答案:

答案 0 :(得分:10)

我认为你可以通过GetType来实现:

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

答案 1 :(得分:5)

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

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

BaseEntity.MyName
"BaseEntity"

BlueEntitiy.MyName
"BlueEntity"
编辑:Doh,高尔基打败了我。

答案 2 :(得分:2)

C#实现了一种查看名为Reflection的对象的方法。这可以返回有关您正在使用的对象的信息。

GetType()函数返回您调用它的类的名称。您可以像这样使用它:

return MyObject.GetType().Name;

反思可以做很多事情。如果您想了解更多有关反思的信息,可以在以下网站上阅读:

答案 3 :(得分:1)

将您的foreach语句更改为以下

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

答案 4 :(得分:-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

使用yr代码:

// 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);}

答案 5 :(得分:-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) {}
}