【问题标题】:Getting class name inside the class itself [duplicate]在类本身中获取类名[重复]
【发布时间】:2012-12-14 06:15:57
【问题描述】:

可能重复:
C# getting its own class name

对于 Visual Studio,我想创建一个类模板并使用一个包含类本身名称的字符串字段。有可能吗?

例如:

public class MyClass
{
     public string TAG = GetClassName(this);
}       

【问题讨论】:

    标签: c#


    【解决方案1】:

    在谈论非静态方法时,请使用Object.GetType Method,它返回实例的确切运行时类型(对Type Class 实例的引用):

    this.GetType().Name
    

    谈到静态方法时,请使用MethodBase Class 及其GetCurrentMethod Method

    Type t = MethodBase.GetCurrentMethod().DeclaringType;
    //t.Name 
    

    但是,请参阅this post on SO 了解更多信息。

    【讨论】:

      【解决方案2】:
      public string GetClassName(object item)
      {
        return typeof(item).Name;
      }
      

      【讨论】:

      • 显然这不会编译。
      【解决方案3】:

      尝试以下操作:

      this.GetType().Name
      

      Type.Name -> 获取当前成员的名字。

      【讨论】:

        猜你喜欢
        • 2020-09-25
        • 1970-01-01
        • 2016-01-04
        • 1970-01-01
        • 2016-12-14
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多